org.graalvm.polyglot.Context Java Examples

The following examples show how to use org.graalvm.polyglot.Context. 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: DeviceTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #2
Source File: HashemSharedCodeSeparatedEnvTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Before
public void initializeEngines() {
    osRuntime = new ByteArrayOutputStream();
    engine = Engine.newBuilder().out(osRuntime).err(osRuntime).build();

    os1 = new ByteArrayOutputStream();
    os2 = new ByteArrayOutputStream();

    int instances = HashemLanguage.counter.get();
    // @formatter:off
    e1 = Context.newBuilder("hashemi").engine(engine).out(os1).allowPolyglotAccess(PolyglotAccess.ALL).build();
    e1.getPolyglotBindings().putMember("extra", 1);
    e2 = Context.newBuilder("hashemi").engine(engine).out(os2).allowPolyglotAccess(PolyglotAccess.ALL).build();
    e2.getPolyglotBindings().putMember("extra", 2);
    e1.initialize("hashemi");
    e2.initialize("hashemi");
    assertEquals("One HashemLanguage instance created", instances + 1, HashemLanguage.counter.get());
}
 
Example #3
Source File: DeviceArrayCopyFunctionTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #4
Source File: HostMapSpec.java    From swim with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpecializedMap() {
  try (Context context = Context.create()) {
    final JavaHostRuntime runtime = new JavaHostRuntime();
    final VmBridge bridge = new VmBridge(runtime, "js");
    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));

    assertNotNull(context.eval("js", "testMap.has").as(Object.class));
    assertNull(context.eval("js", "testMap.containsKey").as(Object.class));
    assertTrue(context.eval("js", "testMap.has('foo')").asBoolean());
    assertFalse(context.eval("js", "testMap.has('bar')").asBoolean());
  }
}
 
Example #5
Source File: HostThrowableSpec.java    From swim with Apache License 2.0 6 votes vote down vote up
@Test
public void testThrowables() {
  try (Context context = Context.create()) {
    final JavaHostRuntime runtime = new JavaHostRuntime();
    final VmBridge bridge = new VmBridge(runtime, "js");
    runtime.addHostLibrary(JavaBase.LIBRARY);

    final Throwable testCause = new Throwable("test cause");
    final Throwable testThrowable = new Throwable("test throwable", testCause);

    final Value bindings = context.getBindings("js");
    bindings.putMember("testThrowable", bridge.hostToGuest(testThrowable));

    assertEquals(bridge.guestToHost(context.eval("js", "testThrowable")), testThrowable);
    assertEquals(context.eval("js", "testThrowable.getMessage()").asString(), "test throwable");
    assertEquals(bridge.guestToHost(context.eval("js", "testThrowable.getCause()")), testCause);
  }
}
 
Example #6
Source File: ItemTypeSpec.java    From swim with Apache License 2.0 6 votes vote down vote up
@Test
public void testItems() {
  try (Context context = Context.create()) {
    final JavaHostRuntime runtime = new JavaHostRuntime();
    final VmBridge bridge = new VmBridge(runtime, "js");
    runtime.addHostLibrary(SwimStructure.LIBRARY);

    final org.graalvm.polyglot.Value bindings = context.getBindings("js");
    bindings.putMember("absent", bridge.hostToGuest(Item.absent()));
    bindings.putMember("extant", bridge.hostToGuest(Item.extant()));
    bindings.putMember("empty", bridge.hostToGuest(Item.empty()));

    assertEquals(bridge.guestToHost(context.eval("js", "absent")), Item.absent());
    assertEquals(context.eval("js", "absent.isDefined()").asBoolean(), false);
    assertEquals(context.eval("js", "absent.isDistinct()").asBoolean(), false);

    assertEquals(bridge.guestToHost(context.eval("js", "extant")), Item.extant());
    assertEquals(context.eval("js", "extant.isDefined()").asBoolean(), true);
    assertEquals(context.eval("js", "extant.isDistinct()").asBoolean(), false);

    assertEquals(bridge.guestToHost(context.eval("js", "empty")), Item.empty());
    assertEquals(context.eval("js", "empty.isDefined()").asBoolean(), true);
    assertEquals(context.eval("js", "empty.isDistinct()").asBoolean(), true);
  }
}
 
Example #7
Source File: SqueakLanguageProvider.java    From trufflesqueak with MIT License 6 votes vote down vote up
@Override
public Collection<? extends Snippet> createStatements(final Context context) {
    final Collection<Snippet> statements = new ArrayList<>();
    addStatementSnippet(context, statements, "IdentityBlock", "[ :p | p ]", ANY, ANY);
    addStatementSnippet(context, statements, "class", "[ :p | p class ]", OBJECT, ANY);
    addStatementSnippet(context, statements, "basicSize", "[ :p | p basicSize ]", NUMBER, ANY);
    addStatementSnippet(context, statements, "hash", "[ :p | p hash ]", NUMBER, ANY);
    addStatementSnippet(context, statements, "isNil", "[ :p | p isNil ]", BOOLEAN, ANY);
    addStatementSnippet(context, statements, "notNil", "[ :p | p notNil ]", BOOLEAN, ANY);
    addStatementSnippet(context, statements, "printString", "[ :p | p printString ]", STRING, ANY);

    addStatementSnippet(context, statements, "ifTrue:", "[ :p | | x | x := false. p ifTrue: [ true ] ]", ANY, BOOLEAN);
    addStatementSnippet(context, statements, "ifTrue:ifFalse:", "[ :p | p ifTrue: [ true ] ifFalse: [ false ] ]", BOOLEAN, BOOLEAN);
    addStatementSnippet(context, statements, "ifFalse:", "[ :p | p ifFalse: [ true ] ]", ANY, BOOLEAN);
    addStatementSnippet(context, statements, "ifFalse:ifTrue:", "[ :p | p ifFalse: [ -1 ] ifTrue: [ 1 ] ]", NUMBER, BOOLEAN);

    addStatementSnippet(context, statements, "and:", "[ :p1 :p2 | p1 and: p2 ]", ANY, BOOLEAN, ANY);
    addStatementSnippet(context, statements, "or:", "[ :p1 :p2 | p1 or: p2 ]", ANY, BOOLEAN, ANY);

    addStatementSnippet(context, statements, "ifNil:", "[ :p | | x | x := false. p ifNil: [ x := true ]. x ]", BOOLEAN, ANY);
    addStatementSnippet(context, statements, "ifNil:ifNotNil:", "[ :p | p ifNil: [ true ] ifNotNil: [ false ] ]", BOOLEAN, ANY);
    addStatementSnippet(context, statements, "ifNotNil:", "[ :p | | x | x := -1. p ifNotNil: [ x := 1 ]. x ]", NUMBER, ANY);
    addStatementSnippet(context, statements, "ifNotNil:ifNil:", "[ :p | p ifNotNil: [ 1 ] ifNil: [ -1 ] ]", NUMBER, ANY);

    return statements;
}
 
Example #8
Source File: SqueakLanguageProvider.java    From trufflesqueak with MIT License 6 votes vote down vote up
@Override
public Collection<? extends Snippet> createValueConstructors(final Context context) {
    final Collection<Snippet> snippets = new ArrayList<>();
    addValueConstructor(context, snippets, "true", BOOLEAN, "[ true ]");
    addValueConstructor(context, snippets, "false", BOOLEAN, "[ false ]");
    addValueConstructor(context, snippets, "nil", NULL, "[ nil ]");
    addValueConstructor(context, snippets, "SmallInteger", NUMBER, "[ 24 ]");
    addValueConstructor(context, snippets, "SmallFloat", NUMBER, "[ 1.23 ]");
    addValueConstructor(context, snippets, "ByteString", STRING, "[ 'spam' ]");
    addValueConstructor(context, snippets, "ByteSymbol", STRING, "[ #bar ]");
    addValueConstructor(context, snippets, "Array:Empty", array(ANY), "[ #() ]");
    addValueConstructor(context, snippets, "Array:SmallIntegers", array(NUMBER), "[ #(8 2 4) ]");
    addValueConstructor(context, snippets, "Array:SmallFloats", array(NUMBER), "[ #(2.3 1.2 3.4) ]");
    addValueConstructor(context, snippets, "Array:ByteStrings", array(STRING), "[ #('foo' 'bar') ]");
    addValueConstructor(context, snippets, "Array:Mixed", array(union(BOOLEAN, NULL, NUMBER, STRING)), "[ #(true false nil 24 'bar') ]");
    addValueConstructor(context, snippets, "Object:Empty", OBJECT, "[ Object new ]");
    addValueConstructor(context, snippets, "Object:Smalltalk", OBJECT, "[ Smalltalk ]");
    addValueConstructor(context, snippets, "Object:SpecialObjectsArray", OBJECT, "[ Smalltalk specialObjectsArray ]");
    addValueConstructor(context, snippets, "Class:Object", INSTANTIABLE, "[ Object ]");
    addValueConstructor(context, snippets, "CompiledMethod:Object>>#hash", EXECUTABLE, "[ Object>>#hash ]");
    addValueConstructor(context, snippets, "BlockClosure", EXECUTABLE, "[ [ 42 ] ]");
    return snippets;
}
 
Example #9
Source File: HashemWebServerTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Before
public void initEngine() throws Exception {
    context = Context.newBuilder().allowCreateThread(true).allowAllAccess(true).build();

    // @formatter:off
    context.eval("hashemi",
            "bebin server() {\n" +
                    "  server1 = webserver(9091);" +
                    "  addHandler(server1,x);" +
                    "  start(server1);" +
                    "}\n" +
                    "bebin x() {" +
                    "bechap(called);" +
                    " javab  = jadid(); " +
                    " javab.status = 202;" +
                    " javab.body= \"Dorood Jahan\";" +
                    " bede javab;" +
                    "}"
    );
    // @formatter:on

    server = context.getBindings("hashemi").getMember("server");
}
 
Example #10
Source File: DeviceTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCanReadSomeDeviceProperties() {
    try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) {
        Value devices = ctx.eval("grcuda", "getdevices()");
        for (int i = 0; i < devices.getArraySize(); ++i) {
            Value device = devices.getArrayElement(i);
            Value prop = device.getMember("properties");
            // Sanity tests on some of the properties
            // device name is a non-zero string
            assertTrue(prop.getMember("deviceName").asString().length() > 0);

            // compute capability is at least compute Kepler (3.0)
            assertTrue(prop.getMember("computeCapabilityMajor").asInt() >= 3);

            // there is at least one multiprocessors
            assertTrue(prop.getMember("multiProcessorCount").asInt() > 0);

            // there is some device memory
            assertTrue(prop.getMember("totalDeviceMemory").asLong() > 0L);
        }
    }
}
 
Example #11
Source File: HashemFactorialTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Before
public void initEngine() throws Exception {
    context = Context.create();
    // @formatter:off
    context.eval("hashemi", "\n" +
            "bebin fac(n) {\n" +
            "  age (n <= 1) bood {\n" +
            "    bede 1;\n" +
            "  }\n" +
            "  prev = fac(n - 1);\n" +
            "  bede prev * n;\n" +
            "}\n"
    );
    // @formatter:on
    factorial = context.getBindings("hashemi").getMember("fac");
}
 
Example #12
Source File: SqueakLanguageProvider.java    From trufflesqueak with MIT License 6 votes vote down vote up
@Override
public Collection<? extends Snippet> createExpressions(final Context context) {
    final Collection<Snippet> snippets = new ArrayList<>();

    // arithmetic
    addExpressionSnippet(context, snippets, "*", "[ :x :y | x * y ]", NUMBER_AND_OBJECT, NUMBER, NUMBER);
    addExpressionSnippet(context, snippets, "+", "[ :x :y | x + y ]", NUMBER_AND_OBJECT, NUMBER, NUMBER);
    addExpressionSnippet(context, snippets, "-", "[ :x :y | x - y ]", NUMBER_AND_OBJECT, NUMBER, NUMBER);
    addExpressionSnippet(context, snippets, "/", "[ :x :y | x / y ]", NUMBER_AND_OBJECT, NUMBER, NUMBER);

    // comparison
    addExpressionSnippet(context, snippets, "<", "[ :x :y | x < y ]", BOOLEAN, NUMBER, NUMBER);
    addExpressionSnippet(context, snippets, "<=", "[ :x :y | x <= y ]", BOOLEAN, NUMBER, NUMBER);
    addExpressionSnippet(context, snippets, "=", "[ :x :y | x = y ]", BOOLEAN, ANY, ANY);
    addExpressionSnippet(context, snippets, ">", "[ :x :y | x > y ]", BOOLEAN, NUMBER, NUMBER);
    addExpressionSnippet(context, snippets, ">=", "[ :x :y | x >= y ]", BOOLEAN, NUMBER, NUMBER);

    addExpressionSnippet(context, snippets, "[ = ]", "[ [ :x :y | x = y ] ]", TypeDescriptor.executable(ANY, ANY, ANY));

    return snippets;
}
 
Example #13
Source File: Main.java    From sieve with MIT License 6 votes vote down vote up
private static void execute(Integer repeat) throws Exception {
    // executing ruby currently requires all access flag to be set.
    Context vm = Context.newBuilder().allowAllAccess(true).build();

    if (repeat != null) {
        vm.eval("js", "count=" + repeat);
    }

    File scriptDir = findScriptDir();
    Source python = Source.newBuilder("python", new File(scriptDir, "sieve.py")).build();
    Source ruby = Source.newBuilder("ruby", new File(scriptDir, "sieve.rb")).build();
    Source js = Source.newBuilder("js", new File(scriptDir, "sieve.js")).build();

    vm.eval(python);
    vm.eval(ruby);
    vm.eval(js);
}
 
Example #14
Source File: BindTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void callWithInoutArgument(String... bindArgs) {
    try (Context polyglot = Context.newBuilder().allowAllAccess(true).build()) {
        Value cu = polyglot.eval("grcuda", "CU");
        Value inoutDeviceArray = cu.getMember("DeviceArray").execute("int", numElements);
        for (int i = 0; i < numElements; i++) {
            inoutDeviceArray.setArrayElement(i, Integer.valueOf(i));
        }

        // get function from shared library
        Value bind = cu.getMember("bind");
        Value function = bindArgs.length > 1 ? bind.execute(dynamicLibraryFile, bindArgs[0], bindArgs[1])
                        : bind.execute(dynamicLibraryFile, bindArgs[0]);
        assertNotNull(function);

        // call function
        int blocks = 80;
        int threadsPerBlock = 256;
        function.execute(blocks, threadsPerBlock, inoutDeviceArray, numElements);

        // verify result
        for (int i = 0; i < numElements; i++) {
            assertEquals(i + 1, inoutDeviceArray.getArrayElement(i).asInt());
        }
    }
}
 
Example #15
Source File: DeviceArrayCopyFunctionTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #16
Source File: DeviceArrayCopyFunctionTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDeviceArrayCopyToDeviceArray() {
    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);
        }
        sourceDeviceArray.invokeMember("copyTo", destinationDeviceArray, numElements);
        // Verify content of device array
        for (int i = 0; i < numElements; ++i) {
            assertEquals(i + 1, destinationDeviceArray.getArrayElement(i).asInt());
        }
    }
}
 
Example #17
Source File: MultiDimArrayTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test2DimArrayRowMajorFromConstructor() {
    // 2-dimensional array through DeviceArray constructor (row-major)
    try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
        Value deviceArrayContructor = context.eval("grcuda", "DeviceArray");
        final int numDim1 = 19;
        final int numDim2 = 53;
        Value matrix = deviceArrayContructor.execute("int", numDim1, numDim2);
        assertEquals(numDim1, matrix.getArraySize());
        assertEquals(numDim2, matrix.getArrayElement(0).getArraySize());
        for (int i = 0; i < numDim1; i++) {
            for (int j = 0; j < numDim2; j++) {
                matrix.getArrayElement(i).setArrayElement(j, i * numDim2 + j);
            }
        }
        for (int i = 0; i < numDim1; i++) {
            for (int j = 0; j < numDim2; j++) {
                assertEquals(i * numDim2 + j, matrix.getArrayElement(i).getArrayElement(j).asInt());
            }
        }
    }
}
 
Example #18
Source File: MultiDimArrayTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test2DimArrayRowMajorFromPolyglotExpr() {
    // 2-dimensional array through polyglot expression "int[19][53]"
    try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
        final int numDim1 = 19;
        final int numDim2 = 53;
        String code = String.format("int[%d][%d]", numDim1, numDim2);
        Value matrix = context.eval("grcuda", code);
        assertEquals(numDim1, matrix.getArraySize());
        assertEquals(numDim2, matrix.getArrayElement(0).getArraySize());
        for (int i = 0; i < numDim1; i++) {
            for (int j = 0; j < numDim2; j++) {
                matrix.getArrayElement(i).setArrayElement(j, i * numDim2 + j);
            }
        }
        for (int i = 0; i < numDim1; i++) {
            for (int j = 0; j < numDim2; j++) {
                assertEquals(i * numDim2 + j, matrix.getArrayElement(i).getArrayElement(j).asInt());
            }
        }
    }
}
 
Example #19
Source File: JalangiTest.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTemplate() throws IOException {
    Context context = Context.create("js");

    // TODO this walks to the NodeProf root to find emptyTemplate.js, is that how it's done?
    File dir = new File(new File(".").getAbsolutePath());
    do {
        dir = dir.getParentFile();
    } while (dir != null && dir.list() != null && !Arrays.asList(dir.list()).contains("mx.nodeprof"));
    assertNotNull(dir);
    assertTrue(dir.isDirectory());

    String templatePath = dir + "/src/ch.usi.inf.nodeprof/js/analysis/trivial/emptyTemplate.js";

    // minimal harness
    context.eval("js", "J$ = {};");

    // evaluate analysis template
    context.eval("js", Source.readFully(new FileReader(templatePath)));

    // retrieve properties (ie. the callbacks) defined in analysis object
    Value v = context.eval("js", "Object.getOwnPropertyNames(J$.analysis)");
    assertTrue(v.hasArrayElements());

    // test callbacks from template
    @SuppressWarnings("unchecked")
    List<String> callbacks = v.as(List.class);
    for (String cb : callbacks) {
        if (JalangiAnalysis.unimplementedCallbacks.contains(cb) || JalangiAnalysis.ignoredCallbacks.contains(cb)) {
            // nothing to test
            continue;
        }
        // for all other callbacks, check if they map to a tag
        assertNotNull("not in callback map: " + cb, JalangiAnalysis.callbackMap.get(cb));
        assertTrue("does not map to any tag: " + cb, JalangiAnalysis.callbackMap.get(cb).size() > 0);
    }
}
 
Example #20
Source File: MultiDimArrayTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void test2DimArrayOutOfBoundsOnReadAccess() {
    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 read access
        matrix.getArrayElement(numDim1);
    }
}
 
Example #21
Source File: DeviceTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetDevicesMatchesAllGetDevice() {
    try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) {
        Value devices = ctx.eval("grcuda", "getdevices()");
        Value getDevice = ctx.eval("grcuda", "getdevice");
        for (int i = 0; i < devices.getArraySize(); ++i) {
            Value deviceFromArray = devices.getArrayElement(i);
            Value deviceFromFunction = getDevice.execute(i);
            assertEquals(i, deviceFromArray.getMember("id").asInt());
            assertEquals(i, deviceFromFunction.getMember("id").asInt());
        }
    }
}
 
Example #22
Source File: DeviceTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #23
Source File: HashemInstrumentTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * Test that we reenter a node whose execution was interrupted. Unwind just the one node off.
 */
@Test
public void testRedoIO() throws Throwable {
    String code = "bebin azinja() {\n" +
            "  a = bekhoon();\n" +
            "  bede a;\n" +
            "}\n";
    final Source ioWait = Source.newBuilder("hashemi", code, "testing").build();
    final TestRedoIO[] redoIOPtr = new TestRedoIO[1];
    InputStream strIn = new ByteArrayInputStream("O.K.".getBytes());
    InputStream delegateInputStream = new InputStream() {
        @Override
        public int read() throws IOException {
            synchronized (HashemInstrumentTest.class) {
                // Block reading before we do unwind:
                if (redoIOPtr[0].beforePop) {
                    redoIOPtr[0].inRead.release();
                    try {
                        HashemInstrumentTest.class.wait();
                    } catch (InterruptedException ex) {
                        throw new RuntimeInterruptedException();
                    }
                }
            }
            return strIn.read();
        }
    };
    Engine engine = Engine.newBuilder().in(delegateInputStream).build();
    TestRedoIO redoIO = engine.getInstruments().get("testRedoIO").lookup(TestRedoIO.class);
    redoIOPtr[0] = redoIO;
    redoIO.inRead.drainPermits();
    Context context = Context.newBuilder().engine(engine).build();
    Value ret = context.eval(ioWait);
    assertEquals("O.K.", ret.asString());
    assertFalse(redoIO.beforePop);
}
 
Example #24
Source File: HashemJavaInteropExceptionTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@HostAccess.Export
public void validateNested() 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");
        test.execute(Validator.this);
    }
}
 
Example #25
Source File: SqueakMessageInterceptor.java    From trufflesqueak with MIT License 5 votes vote down vote up
public static void enableIfRequested(final SqueakLanguage.Env env) {
    if (env.getOptions().hasBeenSet(SqueakOptions.InterceptMessages)) {
        /* Looking up instrument to activate it. */
        breakpoints = (DEFAULTS + "," + env.getOptions().get(SqueakOptions.InterceptMessages)).split(",");
        Context.getCurrent().getEngine().getInstruments().get(ID).lookup(SqueakMessageInterceptor.class);
    }
}
 
Example #26
Source File: DeviceArrayFreeTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(expected = PolyglotException.class)
public void testMultiDimDeviceArrayAccessAfterFreeThrows() {
    try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) {
        // create DeviceArray
        Value createDeviceArray = ctx.eval("grcuda", "DeviceArray");
        Value deviceArray = createDeviceArray.execute("int", 100, 100);
        deviceArray.invokeMember("free");
        deviceArray.getArrayElement(0).setArrayElement(0, 42); // throws
    }
}
 
Example #27
Source File: HashemWebServerTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
    public void factorialOf3() throws Exception {
        context = Context.newBuilder().allowCreateThread(true).allowAllAccess(true).out(System.out).build().create();
        ObjectMapper mapper = new ObjectMapper();
        final HashMap jsonNode = mapper.readValue("{\"person\":{\"name\":\"soroosh\"}}", JsonMap.class);


        // @formatter:off
        context.eval("hashemi",
                "bebin server(request) {\n" +
                        "  bechap(\"req is \"+ request.get(\"person\"));" +
                        "  server1 = webserver(9091);" +
//                        "  server2 = webserver(9092);" +
                        "  start(server1);" +
//                        "  start(server2);" +
                        "  addHandler(server1,x);" +
                        " start(server1); " +
                        "}\n" +
                        "bebin x() {" +
                        "bechap(called);" +
                        "}"
        );
        // @formatter:on

        server = context.getBindings("hashemi").getMember("server");
        System.out.println(server.execute(jsonNode));

        context.close();
    }
 
Example #28
Source File: DeviceArrayFreeTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCanInvokeFreeMultiDimDeviceArray() {
    try (Context ctx = Context.newBuilder().allowAllAccess(true).build()) {
        // create DeviceArray
        Value createDeviceArray = ctx.eval("grcuda", "DeviceArray");
        Value deviceArray = createDeviceArray.execute("int", 100, 100);
        assertTrue(deviceArray.canInvokeMember("free"));
        deviceArray.invokeMember("free");
        // check that freed flag set
        assertTrue(deviceArray.hasMember("isMemoryFreed"));
        assertTrue(deviceArray.getMember("isMemoryFreed").asBoolean());
    }
}
 
Example #29
Source File: HashemDebugALot.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void test() {
    try (Engine engine = Engine.newBuilder().out(out).err(err).allowExperimentalOptions(true).option("debugalot", "true").build()) {
        try (Context context = Context.newBuilder().engine(engine).build()) {
            context.eval(slCode);
        }
    }
    String log = out.toString();
    String successMessage = "Executed successfully:";
    int index = log.lastIndexOf(successMessage);
    Assert.assertTrue(log, index > 0);
    String success = log.substring(index + successMessage.length()).trim();
    Assert.assertEquals(log, "TRUE", success);
}
 
Example #30
Source File: SqueakLanguageProvider.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
public Collection<? extends Source> createInvalidSyntaxScripts(final Context context) {
    final Collection<Source> scripts = new ArrayList<>();
    addSource(scripts, "MissingBracket", "[ :p | p");
    addSource(scripts, "Invalid", "$#%^&*");
    return scripts;
}