org.graalvm.polyglot.Source Java Examples

The following examples show how to use org.graalvm.polyglot.Source. 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: GraalScriptRunner.java    From citeproc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Convert arguments that should be passed to a JavaScript function
 * @param args the arguments
 * @return the converted arguments or `args` if conversion was not necessary
 * @throws IOException if an argument could not be converted
 */
private Object[] convertArguments(Object[] args) throws IOException {
    Object[] copy = args;
    for (int i = 0; i < args.length; ++i) {
        Object v = args[i];
        Object o = v;
        if (v instanceof JsonObject || v instanceof Collection ||
                (v != null && v.getClass().isArray()) || v instanceof Map) {
            String so = createJsonBuilder().toJson(v).toString();
            Source src = Source.newBuilder("js", "(" + so + ")", "parseMyJSON")
                    .cached(false) // we'll most likely never convert the same object again
                    .build();
            o = ctx.eval(src);
        } else if (v instanceof VariableWrapper) {
            o = new VariableWrapperWrapper((VariableWrapper)o);
        }
        if (o != v) {
            if (copy == args) {
                copy = Arrays.copyOf(args, args.length);
            }
            copy[i] = o;
        }
    }
    return copy;
}
 
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: HashemJavaInteropExceptionTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@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 #4
Source File: HashemDebugDirectTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
private static Source createFactorialWithDebugger() {
    return Source.newBuilder("hashemi", "bebin test() {\n" +
                    "  res = fac(2);\n" +
                    "  bechap(res);\n" +
                    "  bede res;\n" +
                    "}\n" +
                    "bebin fac(n) {\n" +
                    "  age (n <= 1) bood {\n" +
                    "    bede 1;\n" +
                    "  }\n" +
                    "  nMinusOne = n - 1;\n" +
                    "  nMOFact = fac(nMinusOne);\n" +
                    "  debugger;\n" +
                    "  res = n * nMOFact;\n" +
                    "  bede res;\n" +
                    "}\n", "factorial.hashem").buildLiteral();
}
 
Example #5
Source File: HashemDebugDirectTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@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 #6
Source File: HashemDebugDirectTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@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 #7
Source File: HashemInteropObjectTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Test
public void testObject() {
    final Source src = Source.newBuilder("hashemi", "bebin azinja() {o = jadid(); o.a = 10; o.b = \"B\"; bede o;}", "testObject.hashem").buildLiteral();
    final Value obj = context.eval(src);
    Assert.assertTrue(obj.hasMembers());

    Value a = obj.getMember("a");
    Assert.assertNotNull(a);
    Assert.assertTrue(a.isNumber());
    Assert.assertEquals(10, a.asInt());

    Value b = obj.getMember("b");
    Assert.assertNotNull(b);
    Assert.assertTrue(b.isString());
    Assert.assertEquals("B", b.asString());

    obj.putMember("a", b);
    a = obj.getMember("a");
    Assert.assertTrue(a.isString());
    Assert.assertEquals("B", a.asString());

    obj.removeMember("a");
    Assert.assertFalse(obj.hasMember("a"));

    Assert.assertEquals("[b]", obj.getMemberKeys().toString());
}
 
Example #8
Source File: JsAssertValidator.java    From java-bean-validation-extension with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(Object value, ConstraintValidatorContext validatorContext) {

    String attributeName = annotation.attributeName();
    String expression = annotation.value();

    Source source = sources.get(expression);

    if (null == source) {
        source = Source.create("js", expression);
        sources.put(expression, source);
    }

    context.getBindings("js")
           .putMember(attributeName, value);

    return context.eval(source).asBoolean();
}
 
Example #9
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 #10
Source File: HashemExceptionTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Test
public void testGuestLanguageError() {
    try {
        String source = "bebin bar() { x = 1 / \"asdf\"; }\n" +
                "bebin foo() { bede bar(); }\n" +
                "bebin azinja() { foo(); }";
        ctx.eval(Source.newBuilder("hashemi", source, "script.hashemi").buildLiteral());
        fail();
    } catch (PolyglotException e) {
        assertTrue(e.isGuestException());

        Iterator<StackFrame> frames = e.getPolyglotStackTrace().iterator();
        assertGuestFrame(frames, "hashemi", "bar", "script.hashemi", 18, 28);
        assertGuestFrame(frames, "hashemi", "foo", "script.hashemi", 51, 56);
        assertGuestFrame(frames, "hashemi", "azinja", "script.hashemi", 77, 82);
        assertHostFrame(frames, Context.class.getName(), "eval");
        assertHostFrame(frames, HashemExceptionTest.class.getName(), "testGuestLanguageError");

        // only host frames trailing
        while (frames.hasNext()) {
            assertTrue(frames.next().isHostFrame());
        }
    }
}
 
Example #11
Source File: HashemDebugDirectTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@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 #12
Source File: HashemiMain.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
/**
 * The main entry point.
 */
public static void main(String[] args) throws IOException {
    Source source;
    Map<String, String> options = new HashMap<>();
    String file = null;
    for (String arg : args) {
        if (parseOption(options, arg)) {
            continue;
        } else {
            if (file == null) {
                file = arg;
            }
        }
    }

    if (file == null) {
        // @formatter:off
        source = Source.newBuilder(HASHEMI, new InputStreamReader(System.in), "<stdin>").build();
        // @formatter:on
    } else {
        source = Source.newBuilder(HASHEMI, new File(file)).build();
    }

    System.exit(executeSource(source, System.in, System.out, options));
}
 
Example #13
Source File: HashemJavaInteropExceptionTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@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 #14
Source File: JavaScriptLanguage.java    From crate with Apache License 2.0 5 votes vote down vote up
static Value resolvePolyglotFunctionValue(String functionName, String script) throws IOException {
    var context = Context.newBuilder("js")
        .engine(ENGINE)
        .allowHostAccess(HOST_ACCESS)
        .build();
    var source = Source.newBuilder("js", script, functionName).build();
    context.eval(source);
    var polyglotFunctionValue = context.getBindings("js").getMember(functionName);
    if (polyglotFunctionValue == null) {
        throw new IllegalArgumentException(
            "The name of the function signature '" + functionName + "' doesn't match " +
            "the function name in the function definition.");
    }
    return polyglotFunctionValue;
}
 
Example #15
Source File: HashemTCKLanguageProvider.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static Snippet loadScript(
                final Context context,
                final String resourceName,
                final TypeDescriptor type,
                final ResultVerifier verifier) {
    try {
        final Source src = createSource(resourceName);
        return Snippet.newBuilder(src.getName(), context.eval(src), type).resultVerifier(verifier).build();
    } catch (IOException ioe) {
        throw new AssertionError("IOException while creating a test script.", ioe);
    }
}
 
Example #16
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 #17
Source File: SqueakLanguageProvider.java    From trufflesqueak with MIT License 5 votes vote down vote up
private static void addSource(final Collection<Source> scripts, final String name, final CharSequence code) {
    try {
        scripts.add(Source.newBuilder(SqueakLanguageConfig.ID, code, name).build());
    } catch (final IOException e) {
        throw new AssertionError("IOException while creating a test source.", e);
    }
}
 
Example #18
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;
}
 
Example #19
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 #20
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 #21
Source File: HashemJavaInteropConversionTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testGR7318Object() throws Exception {
    String sourceText = "bebin test(validator) {\n" +
            "  obj = jadid();\n" +
            "  obj.a = jadid();\n" +
            "  obj.b = jadid();\n" +
            "  bede validator.validateObject(obj, obj);\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");
        Value res = test.execute(new Validator());
        assertTrue(res.isNumber() && res.asInt() == 42);
    }
}
 
Example #22
Source File: HashemJavaInteropExceptionTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testTruffleMap() throws Exception {
    String javaMethod = "validateMap";
    String sourceText = "" +
                    "bebin test(validator) {\n" +
                    "  bede validator." + javaMethod + "(jadid());\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(new Validator());
    }
}
 
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: HashemInteropObjectTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@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 #26
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 #27
Source File: HashemParseErrorTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testParseErrorEOF2() {
    try {
        final Source src = Source.newBuilder("hashemi", "function\n", "testSyntaxErrorEOF2.hashem").buildLiteral();
        context.eval(src);
        Assert.assertTrue("Should not reach here.", false);
    } catch (PolyglotException e) {
        Assert.assertTrue("Should be a syntax error.", e.isSyntaxError());
        Assert.assertNotNull("Should have source section.", e.getSourceLocation());
    }
}
 
Example #28
Source File: HashemParseErrorTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testParseErrorEOF1() {
    try {
        final Source src = Source.newBuilder("hashemi", "bebin azinja", "testSyntaxErrorEOF1.hashem").buildLiteral();
        context.eval(src);
        Assert.assertTrue("Should not reach here.", false);
    } catch (PolyglotException e) {
        Assert.assertTrue("Should be a syntax error.", e.isSyntaxError());
        Assert.assertNotNull("Should have source section.", e.getSourceLocation());
    }
}
 
Example #29
Source File: HashemParseErrorTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testParseErrorEmpty() {
    try {
        final Source src = Source.newBuilder("hashemi", "", "testSyntaxErrorEmpty.hashem").buildLiteral();
        context.eval(src);
        Assert.assertTrue("Should not reach here.", false);
    } catch (PolyglotException e) {
        Assert.assertTrue("Should be a syntax error.", e.isSyntaxError());
        Assert.assertNotNull("Should have source section.", e.getSourceLocation());
    }
}
 
Example #30
Source File: HashemParseErrorTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void testParseError() {
    try {
        final Source src = Source.newBuilder("hashemi", "bebin testSyntaxError(a) {break;} function main() {return testSyntaxError;}", "testSyntaxError.hashem").buildLiteral();
        context.eval(src);
        Assert.assertTrue("Should not reach here.", false);
    } catch (PolyglotException e) {
        Assert.assertTrue("Should be a syntax error.", e.isSyntaxError());
        Assert.assertNotNull("Should have source section.", e.getSourceLocation());
    }
}