Java Code Examples for org.graalvm.polyglot.Context#eval()

The following examples show how to use org.graalvm.polyglot.Context#eval() . 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: HashemInstrumentTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
/**
 * Test that we can alter bebin arguments on reenter.
 */
@Test
public void testChangeArgumentsOnReenter() throws Exception {
    String code = "bebin azinja() {\n" +
            "  y = fce(0, 10000);\n" +
            "  bede y;\n" +
            "}\n" +
            "bebin fce(x, z) {\n" +
            "  y = 2 * x;\n" +
            "  age (y < z) bood {\n" +
            "    print(\"A bad error.\");\n" +
            "    bede 0 - 1;\n" +
            "  } na? {\n" +
            "    bede y;\n" +
            "  }\n" +
            "}\n";
    final Source source = Source.newBuilder("hashemi", code, "testing").build();
    Context context = Context.create();
    IncreaseArgOnErrorInstrument incOnError = context.getEngine().getInstruments().get("testIncreaseArgumentOnError").lookup(IncreaseArgOnErrorInstrument.class);
    incOnError.attachOn("A bad error");

    Value ret = context.eval(source);
    assertEquals(10000, ret.asInt());
}
 
Example 2
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 3
Source File: HashemExceptionTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testGuestOverHostPropagation() {
    Context context = Context.newBuilder("hashemi").allowAllAccess(true).build();
    String code = "" +
            "bebin other(x) {" +
            "   bede invalidFunction();" +
            "}" +
            "" +
            "bebin f(test) {" +
            "test.methodThatTakesFunction(other);" +
            "}";

    context.eval("hashemi", code);
    try {
        context.getBindings("hashemi").getMember("f").execute(this);
        fail();
    } catch (PolyglotException e) {
        assertFalse(e.isHostException());
        assertTrue(e.isGuestException());
        Iterator<StackFrame> frames = e.getPolyglotStackTrace().iterator();
        assertTrue(frames.next().isGuestFrame());
        assertGuestFrame(frames, "hashemi", "other", "Unnamed", 24, 41);
        assertHostFrame(frames, "com.oracle.truffle.polyglot.PolyglotFunction", "apply");
        assertHostFrame(frames, "ninja.soroosh.hashem.lang.test.HashemExceptionTest", "methodThatTakesFunction");
        assertGuestFrame(frames, "hashemi", "f", "Unnamed", 58, 93);

        // rest is just unit test host frames
        while (frames.hasNext()) {
            assertTrue(frames.next().isHostFrame());
        }
    }
}
 
Example 4
Source File: HashemTCKLanguageProvider.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static Value eval(final Context context, final String fncDecl, final String functionName) {
    return context.eval(ID,
                    fncDecl +
                                    "\n" +
                                    "bebin azinja() {\n" +
                                    String.format("  return %s;\n", functionName) +
                                    "}");
}
 
Example 5
Source File: HashemTestRunner.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static void run(Context context, Path path, PrintWriter out) throws IOException {
    try {
        /* Parse theHashemisource file. */
        Source source = Source.newBuilder(HashemLanguage.ID, path.toFile()).interactive(true).build();

        /* Call the main entry point, without any arguments. */
        context.eval(source);
    } catch (PolyglotException ex) {
        if (!ex.isInternalError()) {
            out.println(ex.getMessage());
        } else {
            throw ex;
        }
    }
}
 
Example 6
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 7
Source File: JavaScriptSourceLoader.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public Result load(Runtime runtime, Source source) throws Exception {
    RoutesBuilder builder = new EndpointRouteBuilder() {
        @Override
        public void configure() throws Exception {
            final Context context = Context.newBuilder("js").allowAllAccess(true).build();

            try (InputStream is = source.resolveAsInputStream(getContext())) {
                Value bindings = context.getBindings(LANGUAGE_ID);

                // configure bindings
                bindings.putMember("__dsl", new IntegrationConfiguration(this));

                final String script = new String(is.readAllBytes(), StandardCharsets.UTF_8);
                final String wrappedScript = "with (__dsl) { " + script + " }";

                context.eval(LANGUAGE_ID, wrappedScript);

                //
                // Close the polyglot context when the camel context stops
                //
                getContext().addLifecycleStrategy(new LifecycleStrategySupport() {
                    @Override
                    public void onContextStop(CamelContext camelContext) {
                        context.close(true);
                    }
                });
            }
        }
    };

    return Result.on(builder);
}
 
Example 8
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 9
Source File: SLAppFromFile.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Context context = Context.newBuilder().out(os).build();

    String path = args[0];
    Source src = Source.newBuilder("sl", new File(path)).build();
    
    Value result = context.eval(src); // LBREAKPOINT

    assertEquals("Expected result", 42L, result.asLong());
    assertEquals("Expected output", "42\n", os.toString("UTF-8"));
}
 
Example 10
Source File: SLApp.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 11
Source File: GraalEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void pythonDirect() throws Exception {
    final Context ctx = Context.newBuilder().allowAllAccess(true).build();
    Value mul = ctx.eval("python", MUL);
    Value fourtyTwo = mul.execute(6, 7);
    Assert.assertEquals("Fourty two", 42, fourtyTwo.asInt());
}
 
Example 12
Source File: SqueakBasicImageTest.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Test
public void test14ImageSnapshot() {
    final String newImageName = "test14ImageSnapshot.image";
    final String newChangesName = "test14ImageSnapshot.changes";
    evaluate(String.format("Smalltalk saveAs: '%s'", newImageName));
    final TruffleFile newImageFile = image.env.getInternalTruffleFile(image.getImagePath()).getParent().resolve(newImageName);
    final TruffleFile newChangesFile = image.env.getInternalTruffleFile(image.getImagePath()).getParent().resolve(newChangesName);
    assertTrue(newImageFile.exists());
    assertTrue(newChangesFile.exists());
    /* Open the saved image and run code in it. */
    final Context newContext = Context.newBuilder(SqueakLanguageConfig.ID).allowAllAccess(true).option(SqueakLanguageConfig.ID + "." + SqueakLanguageOptions.IMAGE_PATH,
                    newImageFile.getPath()).option(SqueakLanguageConfig.ID + "." + SqueakLanguageOptions.HEADLESS, "true").build();
    newContext.enter();
    try {
        final Value result = newContext.eval(SqueakLanguageConfig.ID, "1 + 2 * 3");
        assertTrue(result.fitsInInt());
        assertEquals(9, result.asInt());
    } finally { /* Cleanup */
        newContext.leave();
        try {
            newImageFile.delete();
            newChangesFile.delete();
        } catch (final IOException e) {
            fail(e.getMessage());
        }
    }
}
 
Example 13
Source File: Main.java    From sieve with MIT License 5 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 ruby = Source.newBuilder("ruby", new File(scriptDir, "sieve.rb")).build();
    Source js = Source.newBuilder("js", new File(scriptDir, "sieve.js")).build();

    vm.eval(ruby);
    vm.eval(js);
}
 
Example 14
Source File: HashemiMain.java    From mr-hashemi with Universal Permissive License v1.0 4 votes vote down vote up
private static int executeSource(Source source, InputStream in, PrintStream out, Map<String, String> options) {
    Context context;
    PrintStream err = System.err;
    try {
        context = Context.newBuilder(HASHEMI)
                .allowCreateThread(true)
                .in(in)
                .out(out)
                .options(options)
                .build();
    } catch (IllegalArgumentException e) {
        err.println(e.getMessage());
        return 1;
    }

    try {
        Value result = context.eval(source);
        final Value bindings = context.getBindings(HASHEMI);
        final boolean hasMainFunction = bindings.getMemberKeys().contains("main");
        final boolean hasAzinjaFunction = bindings.getMemberKeys().contains("azinja");

        if (!hasAzinjaFunction) {
            if (!hasMainFunction) {
                err.println("No bebin azinja() defined in Hashemi source file.");
                return 1;
            }
            err.println("bebin main() is senseless, Please change the starting bebin to \"azinja\".");
            return 1;
        }


        if (!result.isNull()) {
            out.println(result.toString());
        }
        return 0;
    } catch (PolyglotException ex) {
        if (ex.isInternalError()) {
            // for internal errors we print the full stack trace
            ex.printStackTrace();
        } else {
            err.println(ex.getMessage());
        }
        return 1;
    } finally {
        context.close();
    }
}
 
Example 15
Source File: SqueakLanguageProvider.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Value createIdentityFunction(final Context context) {
    return context.eval(SqueakLanguageConfig.ID, "[ :x | x ]");
}
 
Example 16
Source File: SqueakTranscriptForwarder.java    From trufflesqueak with MIT License 4 votes vote down vote up
public void setUp(final Context context) throws IOException {
    transcriptBlock = context.eval(Source.newBuilder(SqueakLanguageConfig.ID, TRANSCRIPT_BLOCK_CODE, TRANSCRIPT_BLOCK_CODE_NAME).build());
}