Top Description Inners Fields Constructors Methods
org.graalvm.polyglot

public final Class Context

extends Object
implements AutoCloseable
Class Inheritance
All Implemented Interfaces
java.lang.AutoCloseable
Imports
java.io.InputStream, .OutputStream, java.nio.file.Path, java.time.Duration, .Instant, .LocalDate, .LocalTime, .ZoneId, .ZonedDateTime, java.util.Collections, .HashMap, .Iterator, .List, .Map, .Map.Entry, .Objects, java.util.concurrent.TimeoutException, java.util.function.Predicate, java.util.logging.Handler, java.util.logging.Level, java.util.stream.StreamSupport, org.graalvm.polyglot.impl.AbstractPolyglotImpl.AbstractContextDispatch, .AbstractPolyglotImpl.IOAccessor, org.graalvm.polyglot.io.FileSystem, .IOAccess, .MessageTransport, .ProcessHandler, org.graalvm.polyglot.proxy.Proxy

A polyglot context for Graal guest languages that allows to evaluate code. A polyglot context represents the global runtime state of all installed and permitted languages. Permitted languages are initialized lazily, when they are used for the first time. For many context operations, a language identifier needs to be specified. A language identifier is unique for each language.

Evaluation

A context allows to evaluate a guest language source code using eval(Source). This is possible by evaluating Source objects or a given language identifier and code String. The evaluation returns either the result value or throws a PolyglotException if a guest language error occurs.

Example for evaluation of a fragment of JavaScript code with a new context:

Context context = Context.create();
Value result = context.eval("js", "42");
assert result.asInt() == 42;
context.close();
In this example:

Configuration

Contexts may be created either with default configuration using the create method or with custom configuration using the builder. Both methods allow to specify a subset of the installed languages as permitted languages. If no language is specified then all installed languages are permitted. Using the builder method input, error and output streams, options, and application arguments may be configured.

Options may be specified for languages, instruments, the engine and the compiler. For language options, the option key consists of the language id plus a dot followed by the option name (e.g. "js.Strict"). For most languages the option names start with an upper-case letter by convention. A list of available options may be received using Language#getOptions(). Instrument options are structured in the same way as language options but start with the instrument id instead.

If system properties are enabled, which they are by default, then all polyglot options maybe specified with the prefix "polyglot." (e.g. "-Dpolyglot.js.Strict=true"). The system properties are read only once when the context or engine instance is created. After that, changes to the system properties have no affect.

Each Graal language performs an initialization step before it can be used to execute code, after which it remains initialized for the lifetime of the context. Initialization is by default lazy and automatic, but initialization can be forced manually if needed.

Example for custom configuration using the context builder:

OutputStream myOut = new BufferedOutputStream()
Context context = Context.newBuilder("js", "R")
                         .out(myOut)
                         .option("js.Strict", "true")
                         .allowAllAccess(true)
                         .build();
context.eval("js", "42");
context.eval("R", "42");
context.close();
In this example:

Bindings

The symbols of the top-most scope of a language can be accessed using the language bindings. Each language provides its own bindings object for a context. The bindings object may be used to read, modify, insert and delete members in the top-most scope of the language. Certain languages may not allow write access to the bindings object. See getBindings(String) for details.

A context instance also provides access to the polyglot bindings. The polyglot bindings are shared between languages and may be used to exchange values. See getPolyglotBindings() for details.

Examples using language bindings from JavaScript:

Context context = Context.create("js");
Value jsBindings = context.getBindings("js")

jsBindings.putMember("foo", 42);
assert context.eval("js", "foo").asInt() == 42;

context.eval("js", "var bar = 42");
assert jsBindings.getMember("bar").asInt() == 42;

assert jsBindings.getMember("Math")
                 .getMember("abs")
                 .execute(-42)
                 .asInt() == 42;
context.close();
In this example:

Host Interoperability

It is often necessary to interact with values of the host runtime and Graal guest languages. Such objects are referred to as host objects. Every Java value that is passed to a Graal language is interpreted according to the specification described in asValue(Object). Also see Value#as(Class) for further details.

By default only public classes, methods, and fields that are annotated with @HostAccess.Export are accessible to the guest language. This policy can be customized using Builder#allowHostAccess(HostAccess) when constructing the context.

Example using a Java object from JavaScript:

public class JavaRecord {
    @HostAccess.Export public int x;

    @HostAccess.Export
    public String name() {
        return "foo";
    }
}
Context context = Context.create();

JavaRecord record = new JavaRecord();
context.getBindings("js").putMember("javaRecord", record);

context.eval("js", "javaRecord.x = 42");
assert record.x == 42;

context.eval("js", "javaRecord.name()").asString().equals("foo");

Error Handling

Program execution may fail when executing a guest language code or when accessing guest language object. Almost all methods in the Context and Value API throw a PolyglotException in case an error occurs. See PolyglotException for further details on error handling.

Isolation

Each context is by default isolated from all other instances with respect to both language evaluation semantics and resource consumption. By default, a new context instance has no access to host resources, like threads, files or loading new host classes. To allow access to such resources either the individual access right must be granted or all access must be set to true.

Contexts can be configured to share certain system resources like ASTs or optimized code by specifying a single underlying engine. See Engine for more details about code sharing.

Context can be configured to allow value sharing between multiple contexts (allowed by default). See Builder#allowValueSharing(boolean) for details.

Proxies

The proxy interfaces allow to mimic guest language objects, arrays, executables, primitives and native objects in Graal languages. Every Graal language will treat proxy instances like objects of that particular language. Multiple proxy interfaces can be implemented at the same time. For example, it is useful to provide proxy values that are objects with members and arrays at the same time.

Thread-Safety

It is safe to use a context instance from a single thread. It is also safe to use it with multiple threads if they do not access the context at the same time. Whether a single context instance may be used from multiple threads at the same time depends on if all initialized languages support it. If initialized languages support multi-threading, then the context instance may be used from multiple threads at the same time. If a context is used from multiple threads and the language does not fit, then an IllegalStateException is thrown by the accessing method.

Meta-data from the context's underlying engine can be retrieved safely by any thread at any time.

A context may be closed from any thread, but only if the context is not currently executing code. If the context is currently executing some code, a different thread may kill the running execution and close the context using close(boolean).

Context Exit

A context is exited naturally by calling the close method. A context may also be exited at the guest application request. There are two ways a guest language may exit.

Pre-Initialization

The context pre-initialization can be used to perform expensive builtin creation in the time of native compilation.

The context pre-initialization is enabled by setting the system property polyglot.image-build-time.PreinitializeContexts to a comma separated list of language ids which should be pre-initialized, for example: -Dpolyglot.image-build-time.PreinitializeContexts=js,python

See com.oracle.truffle.api.TruffleLanguage.patchContext(java.lang.Object, com.oracle.truffle.api.TruffleLanguage.Env) for details about pre-initialization for language implementers.

Since
19.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
public class
Context.Builder

Builder class to construct Context instances.

Field Summary

Modifier and TypeField and Description
pack-priv static final Predicate<String>
pack-priv final Context
pack-priv final AbstractPolyglotImpl.AbstractContextDispatch
private static final Context
pack-priv final Engine
pack-priv static final Predicate<String>
pack-priv final Object
pack-priv static final Predicate<String>

Constructor Summary

AccessConstructor and Description
pack-priv <T>
private
private <T>
Context(Context creatorAPI)

Method Summary

Modifier and TypeMethod and Description
public Value

Returns:

the polyglot value.
asValue
(Object
the host value to convert to a polyglot value.
hostValue
)

Converts a host value to a polyglot value representation.

private void
public void
close(boolean
if true then currently executing contexts will be cancelled, else an IllegalStateException is thrown.
cancelIfExecuting
)

Closes the context and frees up potentially allocated native resources.

public void
close()

Implements java.lang.AutoCloseable.close.

Closes this context and frees up potentially allocated native resources.

public static Context
create(String... permittedLanguages)

Creates a context with default configuration.

public void
enter()

Explicitly enters the context on the current thread.

public boolean
equals(Object
the reference object with which to compare.
obj
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

public Value

Returns:

the evaluation result. The returned instance is never null, but the result might represent a null value.
eval
(Source
a source object to evaluate
source
)

Evaluates a source object by using the language specified in the source.

public Value

Returns:

the evaluation result. The returned instance is never null, but the result might represent a null value.
eval
(String languageId, CharSequence source)

Evaluates a guest language code literal, using a provided language id.

public Value
getBindings(String languageId)

Returns a value that represents the top-most bindings of a language.

public static Context
getCurrent()

Returns the currently entered polyglot context.

public Engine

Returns:

Graal Engine being used by this context
getEngine
()

Provides access to meta-data about the underlying Graal engine.

public Value
getPolyglotBindings()

Returns polyglot bindings that may be used to exchange symbols between the host and guest languages.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for the object.

public boolean

Returns:

true if the language was initialized. Returns false if it was already initialized.
initialize
(String
the identifier of the language to initialize.
languageId
)

Forces the initialization of a language.

public void
interrupt(Duration
specifies the duration the interrupt method will wait for the active threads of the context to be finished. Setting the duration to 0 means wait indefinitely.
timeout
)

Use this method to interrupt this context.

public void
leave()

Explicitly leaves the context on the current thread.

public static Context.Builder

Returns:

a builder that can create a context
newBuilder
(String...
names of languages permitted in the context. If no languages are provided, then all installed languages will be permitted. If an explicit engine was specified then only those languages may be used that were installed and permitted by the specified engine. Languages are validated when the context is built. An IllegalArgumentException will be thrown if an unknown or a language denied by the engine was used.
permittedLanguages
)

Creates a builder for constructing a context with custom configuration.

public Value
parse(Source
a source object to parse
source
)

Parses but does not evaluate a given source by using the language specified in the source and returns a value that can be executed.

public Value
parse(String languageId, CharSequence source)

Parses but does not evaluate a guest language code literal using a provided language id and character sequence and returns a value that can be executed.

public void
resetLimits()

Resets all accumulators of resource limits for the associated context to zero.

public void
safepoint()

Polls safepoints events and executes them for the current thread.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAlltoStringwaitwaitwait