org.graalvm.polyglot.Engine Java Examples

The following examples show how to use org.graalvm.polyglot.Engine. 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: 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 #2
Source File: Truffle.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
private Collection<HeapMonitor> getAllHeapHistogramInstances() {
    List<HeapMonitor> allInstances = new ArrayList();
    Collection<Engine> all = getAllEngineInstances();

    for (Engine engine : all) {
        HeapMonitor heapHisto = HeapMonitor.find(engine);

        if (heapHisto != null) {
            if (!heapHisto.isCollecting()) {
                heapHisto.setCollecting(true);
            }
            allInstances.add(heapHisto);
        }
    }
    return allInstances;
}
 
Example #3
Source File: DebugSLTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static Test suite() throws URISyntaxException {
    final File sdkAPI = new File(Engine.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    final File truffleAPI = new File(TruffleLanguage.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    final File sl = new File(SLLanguage.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    final File antlr4 = new File(org.antlr.v4.runtime.Parser.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    final File junit = new File(TestCase.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    assertTrue("SDK API exists: " + sdkAPI, sdkAPI.exists());
    assertTrue("truffle-api JAR exists: " + truffleAPI, truffleAPI.exists());
    assertTrue("sl JAR exists: " + sl, sl.exists());
    assertTrue("antlr4 JAR exists: " + antlr4, antlr4.exists());
    assertTrue("junit JAR exists: " + junit, junit.exists());

    System.setProperty("graal-sdk.jar", sdkAPI.getAbsolutePath());
    System.setProperty("truffle.jar", truffleAPI.getAbsolutePath());
    System.setProperty("sl.jar", sl.getAbsolutePath());
    System.setProperty("antlr4.jar", antlr4.getAbsolutePath());
    System.setProperty("junit.jar", junit.getAbsolutePath());

    return JPDASupport.createTestSuite(DebugSLTest.class);
}
 
Example #4
Source File: JPDATruffleAccessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static JPDATruffleDebugManager setUpDebugManagerFor(/*Engine*/Object engineObj, boolean includeInternal, boolean doStepInto) {
    trace("setUpDebugManagerFor("+engineObj+", "+doStepInto+")");
    Engine engine = (Engine) engineObj;
    Debugger debugger;
    try {
        debugger = engine.getInstruments().get("debugger").lookup(Debugger.class);
    } catch (NullPointerException npe) {
        // An engine without instruments/debugger. E.g. Engine.EMPTY
        return null;
    }
    synchronized (debugManagers) {
        if (debugManagers.containsKey(debugger)) {
            return null;
        }
    }
    JPDATruffleDebugManager tdm = new JPDATruffleDebugManager(debugger, includeInternal, doStepInto);
    synchronized (debugManagers) {
        debugManagers.put(debugger, tdm);
    }
    return tdm;
}
 
Example #5
Source File: HashemDebugDirectTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Before
public void before() {
    suspendedEvent = null;
    engine = Engine.newBuilder().out(out).err(err).build();
    debugger = engine.getInstruments().get("debugger").lookup(Debugger.class);
    session = debugger.startSession((event) -> {
        suspendedEvent = event;
        performWork();
        suspendedEvent = null;

    });
    context = Context.newBuilder().engine(engine).build();
    run.clear();
}
 
Example #6
Source File: Truffle.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private void setMode(Mode m) {
    Collection<Engine> all = getAllEngineInstances();

    for (Engine engine : all) {
        CPUSampler sampler = CPUSampler.find(engine);

        if (sampler != null) {
            sampler.setMode(m);
        }
    }
}
 
Example #7
Source File: Truffle.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private Collection<CPUSampler> getAllStackTracesInstances() {
    List<CPUSampler> allInstances = new ArrayList();
    Collection<Engine> all = getAllEngineInstances();

    for (Engine engine : all) {
        CPUSampler sampler = CPUSampler.find(engine);

        if (sampler != null) {
            allInstances.add(sampler);
        }
    }
    return allInstances;
}
 
Example #8
Source File: GraalEnginesProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void enumerateLanguages(List<ScriptEngineFactory> arr, Bindings globals) {
    final GraalContext ctx = new GraalContext(globals);
    try (Engine engine = Engine.newBuilder().build()) {
        for (Map.Entry<String, Language> entry : engine.getLanguages().entrySet()) {
            arr.add(new GraalEngineFactory(ctx, entry.getKey(), entry.getValue()));
        }
    }
}
 
Example #9
Source File: GetMIMETypes.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /*
    Method loadLanguageClass = Engine.class.getDeclaredMethod("loadLanguageClass", String.class);
    loadLanguageClass.setAccessible(true);
    Class polyglotEngineClass = (Class) loadLanguageClass.invoke(null, "com.oracle.truffle.api.vm.PolyglotEngine");
    Object builder = polyglotEngineClass.getDeclaredMethod("newBuilder").invoke(null);
    Object polyglotEngine = builder.getClass().getMethod("build").invoke(builder);
    Map languages = (Map) polyglotEngine.getClass().getMethod("getLanguages").invoke(polyglotEngine);
    languages.values().stream().
            flatMap((l) -> {
                Stream<String> stream;
                try {
                    stream = ((Set<String>) l.getClass().getMethod("getMimeTypes").invoke(l)).stream();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return stream;}).distinct().
            forEach((mt) -> System.out.println(mt));
    */
    Engine.create().getLanguages().values().stream().
            flatMap((l) -> l.getMimeTypes().stream()).distinct().
            forEach((mt) -> System.out.println(mt));
    /*
    Set<String> MIMETypes = new HashSet<>();
    Collection<? extends PolyglotEngine.Language> languages = PolyglotEngine.newBuilder().build().getLanguages().values();
    for (PolyglotEngine.Language language : languages) {
        MIMETypes.addAll(language.getMimeTypes());
    }
    for (String mt : MIMETypes) {
        System.out.println(mt);
    }*/
}
 
Example #10
Source File: JsAssertValidator.java    From java-bean-validation-extension with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(JsAssert constraintAnnotation) {
    this.engine = Engine.create();
    this.annotation = constraintAnnotation;
    this.context = Context.newBuilder()
                            .allowAllAccess(true)
                            .engine(this.engine)
                          .build();
}
 
Example #11
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 #12
Source File: HashemSeparatedClassLoadersTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Test
public void sdkAndTruffleLanguageAPIAndSLInSeparateClassLoaders() throws Exception {
    final ProtectionDomain sdkDomain = Engine.class.getProtectionDomain();
    Assume.assumeNotNull(sdkDomain);
    Assume.assumeNotNull(sdkDomain.getCodeSource());
    URL sdkURL = sdkDomain.getCodeSource().getLocation();
    Assume.assumeNotNull(sdkURL);

    URL truffleURL = Truffle.class.getProtectionDomain().getCodeSource().getLocation();
    Assume.assumeNotNull(truffleURL);

    URL slURL = HashemLanguage.class.getProtectionDomain().getCodeSource().getLocation();
    Assume.assumeNotNull(slURL);

    ClassLoader parent = Engine.class.getClassLoader().getParent();

    URLClassLoader sdkLoader = new URLClassLoader(new URL[]{sdkURL}, parent);
    boolean sdkLoaderLoadsTruffleLanguage;
    try {
        Class.forName("com.oracle.truffle.api.TruffleLanguage", false, sdkLoader);
        sdkLoaderLoadsTruffleLanguage = true;
    } catch (ClassNotFoundException cnf) {
        sdkLoaderLoadsTruffleLanguage = false;
    }
    Assume.assumeFalse(sdkLoaderLoadsTruffleLanguage);
    URLClassLoader truffleLoader = new URLClassLoader(new URL[]{truffleURL}, sdkLoader);
    URLClassLoader slLoader = new URLClassLoader(new URL[]{slURL}, truffleLoader);
    Thread.currentThread().setContextClassLoader(slLoader);

    Class<?> engineClass = sdkLoader.loadClass(Engine.class.getName());
    Object engine = engineClass.getMethod("create").invoke(null);
    assertNotNull("Engine has been created", engine);

    Map<?, ?> languages = (Map<?, ?>) engineClass.getMethod("getLanguages").invoke(engine);
    Object lang = languages.get("hashemi");
    assertNotNull("SL language found: " + languages, lang);
}
 
Example #13
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 #14
Source File: TruffleSqueakLauncher.java    From trufflesqueak with MIT License 4 votes vote down vote up
private static String getRuntimeName() {
    try (Engine engine = Engine.create()) {
        return engine.getImplementationName();
    }
}
 
Example #15
Source File: JsKernel.java    From swim with Apache License 2.0 4 votes vote down vote up
protected Engine createJsEngine() {
  // TODO: configure from moduleConfig
  return Engine.newBuilder()
      .build();
}
 
Example #16
Source File: CPUSampler.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
public static CPUSampler find(Engine engine) {
    return null;
}
 
Example #17
Source File: HeapMonitor.java    From visualvm with GNU General Public License v2.0 votes vote down vote up
public static HeapMonitor find(Engine engine) {return null;}