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.
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:
initialized.
int
.
AutoCloseable for use with the Java
try-with-resources statement.
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:
Builder#allowAllAccess(boolean) we grant a new context instance with the same
access privileges as the host virtual machine.
initialized as well.
AutoCloseable for use with the Java try-with-resources
statement.
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:
jsBindings.
foo into to the bindings object and verify that the
object is accessible within the language by reading from a global symbol with the same name.
Math.abs symbol and execute
it with -42. This result is asserted to be 42.
asValue(Object).
Also see Value#as(Class) for further details.
By default only public classes, methods, and fields that are annotated with
@HostAccess. 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");
Context and Value API throw a
PolyglotException in case an error occurs. See PolyglotException for further
details on error handling.
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.
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.
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).
close method. A context may also be exited
at the guest application request. There are two ways a guest language may exit.
PolyglotException with PolyglotException#isExit() returning
true and PolyglotException#getExitStatus() returning the exit status code
specified by the guest application. The special exception does not influence other threads and
does not trigger context close on its own. Closing the context is up to the embedder.
PolyglotException with
PolyglotException#isExit() returning true and
PolyglotException#getExitStatus() returning the exit status code specified by the guest
application. However, the context is closed automatically. The hard exit can be customized using
Builder#useSystemExit(boolean). If true, the context threads are unwound by
calling System#exit(int) with the exit status parameter specified by the guest
application. This operation terminates the whole host application.
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.
| Modifier and Type | Class and Description |
|---|---|
| public class | Context.
Builder class to construct |
| Modifier and Type | Field and Description |
|---|---|
| pack-priv static final Predicate | |
| pack-priv final Context | |
| pack-priv final AbstractPolyglotImpl. | |
| private static final Context | |
| pack-priv final Engine | |
| pack-priv static final Predicate | |
| pack-priv final Object | |
| pack-priv static final Predicate |
| Access | Constructor and Description |
|---|---|
| pack-priv <T> | |
| private | |
| private <T> |
| Modifier and Type | Method and Description |
|---|---|
| public Value | |
| private void | |
| public void | close(boolean
if cancelIfExecuting)true then currently executing contexts will be
cancelled, else an
IllegalStateException is thrown.Closes the context and frees up potentially allocated native resources. |
| public void | close()
Implements java. Closes this context and frees up potentially allocated native resources. |
| public static Context | |
| public void | |
| public boolean | equals(Object
the reference object with which to compare. obj)Overrides java. Indicates whether some other object is "equal to" this one. |
| public Value | |
| public Value | Returns: the evaluation result. The returned instance is nevernull, but the
result might represent a null value.Evaluates a guest language code literal, using a provided |
| public Value | |
| public static Context | |
| public Engine | |
| public Value | getPolyglotBindings()
Returns polyglot bindings that may be used to exchange symbols between the host and guest languages. |
| public int | |
| public boolean | Returns: true if the language was initialized. Returns false if it
was already initialized.the identifier of the language to initialize. languageId)Forces the initialization of a language. |
| public void | |
| public void | |
| public static Context. | Returns: a builder that can create a contextnames of languages permitted in the context. If no languages are
provided, then all installed languages will be permitted. If an explicit
permittedLanguages)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.Creates a builder for constructing a context with custom configuration. |
| public Value | |
| public Value | parse(String languageId, CharSequence source)
Parses but does not evaluate a guest language code literal using a provided
|
| public void | |
| public void |