Introduction

GraalVM allows you to write polyglot applications with a seamless way to pass values from one language to another. With GraalVM there is no copying or marshalling necessary as it is with other polyglot systems. This lets you achieve high performance when language boundaries are crossed. Most of the time there is no additional cost for crossing a language boundary at all.

Often developers have to make uncomfortable compromises that require them to rewrite their software in other languages. For example:

  • “That library is not available in my language. I need to rewrite it.”
  • “That language would be the perfect fit for my problem, but we cannot run it in our environment.”
  • “That problem is already solved in my language, but the language is too slow.”

With GraalVM we aim to allow developers to freely choose the right language for the task at hand without making compromises. Throughout this section you learn how to combine multiple languages using our polyglot APIs.

How to Build Polyglot Applications

The following examples are designed to get you started with a basic polyglot application. Select a section for your Start Language and then select a tab for the Target Language.

Ensure you set up GraalVM and export the GraalVM home directory as the $GRAALVM_HOME before you begin. See Get Started.

Requirement: to start an application with LLVM as a Target Language, make sure to precompile polyglot.c file provided below.

Start from JavaScript / Node.js

Create a file polyglot.js:

  // BEGIN-SNIPPET
var array = Polyglot.eval("R", "c(1,2,42,4)")
console.log(array[2]);
// END-SNIPPET

  
  // BEGIN-SNIPPET
var array = Polyglot.eval("ruby", "[1,2,42,4]")
console.log(array[2]);
// END-SNIPPET

  
  // BEGIN-SNIPPET
var array = Polyglot.eval("python", "[1,2,42,4]")
console.log(array[2]);
// END-SNIPPET

  
  // BEGIN-SNIPPET
var array = new (Java.type("int[]"))(4);
array[2] = 42;
console.log(array[2])
// END-SNIPPET
  
  // BEGIN-SNIPPET
var cpart = Polyglot.evalFile("llvm", "polyglot.bc");
cpart.main()
// END-SNIPPET

  

Run:

$ js --polyglot --jvm polyglot.js
42
$ node --polyglot --jvm polyglot.js
42

Start Language R

Create a file polyglot.R:

 
  # BEGIN-SNIPPET
array <- eval.polyglot("js", "[1,2,42,4]")
print(array[3L])
# END-SNIPPET


  
 
  # BEGIN-SNIPPET
array <- eval.polyglot("ruby", "[1,2,42,4]")
print(array[3L])
# END-SNIPPET


  
 
  # BEGIN-SNIPPET
array <- eval.polyglot("python", "[1,2,42,4]")
print(array[3L])
# END-SNIPPET


  
 
  # BEGIN-SNIPPET
array <- new("int[]", 4)
array[3L] <- 42
print(array[3L])
# END-SNIPPET
  
 
  # BEGIN-SNIPPET
cpart <- eval.polyglot("llvm", path="polyglot.bc")
cpart$main()
# END-SNIPPET

  

Run:

$ Rscript --polyglot --jvm polyglot.R
[1] 42

Start Language Ruby:

Create a file polyglot.rb:

  # BEGIN-SNIPPET
array = Polyglot.eval('js', '[1,2,42,4]')
puts array[2]
# END-SNIPPET

  
  # BEGIN-SNIPPET
array = Polyglot.eval('R', 'c(1L,2L,42L,4L)')
puts array[2]
# END-SNIPPET

  
  # BEGIN-SNIPPET
array = Polyglot.eval('python', '[1,2,42,4]')
puts array[2]
# END-SNIPPET

  
  # BEGIN-SNIPPET
array = Java.type('int[]').new(4)
array[2] = 42
print(array[2])
# END-SNIPPET

  
  # BEGIN-SNIPPET
cpart = Polyglot.eval_file('llvm', 'polyglot.bc')
cpart.main()
# END-SNIPPET

  

Run:

$ ruby --polyglot --jvm polyglot.rb
42

Start Language Python:

Create a file polyglot.py:

  # BEGIN-SNIPPET
import polyglot
array = polyglot.eval(language="js", string="[1,2,42,4]")
print(array[2])
# END-SNIPPET
  
  # BEGIN-SNIPPET
import polyglot
array = polyglot.eval(language="R", string="c(1L,2L,42L,4L)")
print(array[2])
# END-SNIPPET


  
  # BEGIN-SNIPPET
import polyglot
array = polyglot.eval(language="ruby", string="[1,2,42,4]")
print(array[2])
# END-SNIPPET


  
  # BEGIN-SNIPPET
import java
array = java.type("int[]")(4)
array[2] = 42
print(array[2])
# END-SNIPPET
  
  # BEGIN-SNIPPET
import polyglot
cpart = polyglot.eval(language="llvm", path="polyglot.bc")
cpart.main()
# END-SNIPPET

  

Run:

$ graalpython --polyglot --jvm polyglot.py
42

Start Language Java:

Create a file Polyglot.java:

  // BEGIN-SNIPPET
import org.graalvm.polyglot.*;

class Polyglot {
    public static void main(String[] args) {
        Context polyglot = Context.create();
        Value array = polyglot.eval("js", "[1,2,42,4]");
        int result = array.getArrayElement(2).asInt();
        System.out.println(result);
    }
}
// END-SNIPPET
  
  // BEGIN-SNIPPET
import org.graalvm.polyglot.*;

class Polyglot {
    public static void main(String[] args) {
        Context polyglot = Context.newBuilder().
    	    		               allowAllAccess(true).build();
        Value array = polyglot.eval("R", "c(1,2,42,4)");
        int result = array.getArrayElement(2).asInt();
        System.out.println(result);
    }
}
// END-SNIPPET

  
  // BEGIN-SNIPPET
import org.graalvm.polyglot.*;

class Polyglot {
    public static void main(String[] args) {
        Context polyglot = Context.newBuilder().
        		               allowAllAccess(true).build();
        Value array = polyglot.eval("ruby", "[1,2,42,4]");
        int result = array.getArrayElement(2).asInt();
        System.out.println(result);
    }
}
// END-SNIPPET

  
  // BEGIN-SNIPPET
import org.graalvm.polyglot.*;

class Polyglot {
    public static void main(String[] args) {
        Context context = Context.newBuilder().allowIO(true).build();
        Value array = context.eval("python", "[1,2,42,4]");
        int result = array.getArrayElement(2).asInt();
        System.out.println(result);
    }
}
// END-SNIPPET

  
  // BEGIN-SNIPPET
import java.io.*;
import org.graalvm.polyglot.*;

class Polyglot {
    public static void main(String[] args) throws IOException {
        Context polyglot = Context.newBuilder().
        		               allowAllAccess(true).build();
        File file = new File("polyglot.bc");
        Source source = Source.newBuilder("llvm", file).build();
        Value cpart = polyglot.eval(source);
        cpart.getMember("main").execute();
    }
}
// END-SNIPPET

  

Run:

$ javac Polyglot.java
$ java Polyglot
42

Start Language C:

Note: This requires clang to be installed.

Create a file polyglot.c:

 
  // BEGIN-SNIPPET
#include <stdio.h>
#include <polyglot.h>

int main() {
    void *array = polyglot_eval("js", "[1,2,42,4]");
    int element = polyglot_as_i32(polyglot_get_array_element(array, 2));
    printf("%d\n", element);
    return element;
}
// END-SNIPPET

  
 
  // BEGIN-SNIPPET
#include <stdio.h>
#include <polyglot.h>

int main() {
    void *array = polyglot_eval("R", "c(1,2,42,4)");
    int element = polyglot_as_i32(polyglot_get_array_element(array, 2));
    printf("%d\n", element);
    return element;
}
// END-SNIPPET
  
 
  // BEGIN-SNIPPET
#include <stdio.h>
#include <polyglot.h>

int main() {
    void *array = polyglot_eval("ruby", "[1,2,42,4]");
    int element = polyglot_as_i32(polyglot_get_array_element(array, 2));
    printf("%d\n", element);
    return element;
}
// END-SNIPPET
  
 
  // BEGIN-SNIPPET
#include <stdio.h>
#include <polyglot.h>

int main() {
    void *array = polyglot_eval("python", "[1,2,42,4]");
    int element = polyglot_as_i32(polyglot_get_array_element(array, 2));
    printf("%d\n", element);
    return element;
}
// END-SNIPPET
  
 
  // BEGIN-SNIPPET
#include <stdio.h>
#include <polyglot.h>

int main() {
    void *arrayType = polyglot_java_type("int[]");
    void *array = polyglot_new_instance(arrayType, 4);
    polyglot_set_array_element(array, 2, 42);
    int element = polyglot_as_i32(polyglot_get_array_element(array, 2));
    printf("%d\n", element);
    return element;
}
// END-SNIPPET

  

Run:

$ clang -g -O1 -c -emit-llvm -I$GRAALVM_HOME/jre/languages/llvm polyglot.c
$ lli --polyglot --jvm polyglot.bc
42

How Does Polyglot Work

In order to provide foreign polyglot values meaning in the languages we have developed the so-called polyglot interoperability protocol. This interoperability protocol consists of a set of standardized messages that every Graal language implements and uses for foreign polyglot values. The protocol allows GraalVM to support interoperability between any combination of languages without requiring them to know of each other. We plan to gradually improve the protocol to support more and more features over time.

For further details, we recommend reading:

Running Polyglot Applications

With polyglot applications it is often impossible to decide what the primary language of an application is. Therefore, we have added an experimental new launcher called polyglot to GraalVM. For the moment, this launcher runs code for JavaScript, Ruby, and R without requiring to select a primary language. The polyglot launcher does not require the --polyglot option, it is enabled by default.

This is how you can run a polyglot application by using the examples from above:

$ polyglot --jvm polyglot.js polyglot.R polyglot.rb

We have also included a basic experimental shell for multiple languages called the Polyglot Shell. It is useful to quickly test interactive Graal languages. This is how you can start it:

$ polyglot --jvm --shell

GraalVM MultiLanguage Shell 1.0.0-rc10
Copyright (c) 2013-2018, Oracle and/or its affiliates
  JavaScript version 1.0
  Python version 3.7.0
  R version 3.4.0
  Ruby version 2.4.4
Usage:
  Use Ctrl+L to switch language and Ctrl+D to exit.
  Enter -usage to get a list of available commands.
js>

Polyglot Options

Polyglot Options for Graal Language Launchers

We have extended every language launcher with a set of so called polyglot options. Polyglot options allow users of any language launcher to access the options of other Graal languages. The format is: --<languageID>.<property>=<value>. For example the R launcher also supports the --js.atomics=true JavaScript option.

Allowed values for the languageID are:

  • js options for JavaScript.
  • python options for Python.
  • r options for R.
  • ruby options for Ruby.
  • llvm options for LLVM.

Use --help:languages to find out which options are available.

Options for polyglot tools work in the same way with the following format: --<toolID>.<property>=<value>.

Allowed values for <toolID> are:

  • inspect allows debugging with Chrome DevTools.
  • cpusampler collects data about CPU usage.
  • cputracer captures trace information about CPU usage.
  • memtracer captures trace information about memory usage.
  • agent enables remote profiling using the Agent UI.

Use --help:tools to find out which options are available.

Passing Options Programmatically

Options can also be passed programmatically using the Java polyglot API.

Create a file called OptionsTest.java:

import org.graalvm.polyglot.*;

class OptionsTest {

    public static void main(String[] args) {
        Context polyglot = Context.newBuilder()
            .option("js.shared-array-buffer", "true")
            .build();
        // the use of shared array buffer requires
        // the 'js.shared-array-buffer' option to be 'true'
        polyglot.eval("js", "new SharedArrayBuffer(1024)");
    }
}

Run:

$ javac OptionsTest.java
$ java OptionsTest

Please note that tool options can be passed in the same way. Options cannot be modified after the context was created.

Passing Options using JVM Arguments

Every polyglot option can also be passed as a Java system property. Each available option translates to a system property with the polyglot. prefix. For example: -Dpolyglot.js.strict=true sets the default value for a strict interpretation for all JavaScript code that runs in the JVM. Options that were set programmatically take precedence over Java system properties. For languages the following format can be used: -Dpolyglot.<languageID>.<property>=<value> and for tools it is: -Dpolyglot.<toolID>.<property>=<value>.

Create a file called SystemPropertiesTest.java:

import org.graalvm.polyglot.*;

class SystemPropertiesTest {

    public static void main(String[] args) {
        Context polyglot = Context.create();
        // the use of shared array buffer requires
        // the 'js.shared-array-buffer' option to be 'true'
        polyglot.eval("js", "new SharedArrayBuffer(1024)");
    }
}

Run:

$ javac SystemPropertiesTest.java
$ java -Dpolyglot.js.shared-array-buffer=true SystemPropertiesTest

Note: System properties are read once when the polyglot context is created. Subsequent changes have no effect.