Class Context
- All Implemented Interfaces:
AutoCloseable
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 usingeval(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:
- First we create a new context with all permitted languages.
- Next, we evaluate the expression "42" with language "js", which is the language identifier
for JavaScript. Since this is the first time we access JavaScript, it automatically gets
initialized
. - Then, we assert the result value by converting the result value as primitive
int
. - Finally, when a context is no longer needed, it is recommended to explicitly close it to
ensure timely release of resources. While contexts are automatically closed when no longer
strongly reachable, explicit closure is still preferred. Contexts are also
AutoCloseable
, allowing them to be used with the Javatry-with-resources
statement.
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:
- At first, we create a new context and specify permitted languages as parameters.
- Secondly, we set the standard output stream to be used for the context.
- Then, we specify an option for JavaScript language only, by structuring the option key with the language id followed by the option name;
- With
Context.Builder.allowAllAccess(boolean)
we grant a new context instance with the same access privileges as the host virtual machine. - Next, we evaluate the expression "42" with language "js", which is the language identifier
for JavaScript. Since this is the first time we access JavaScript, it first gets
initialized
as well. - Similarly to the previous line, the R language expression gets evaluated.
- Finally, we close the context, since it is no longer needed, to free all allocated resources.
Contexts are also
AutoCloseable
for use with the Javatry-with-resources
statement.
Bindings
The symbols of the top-most scope of a language can be accessed using thelanguage 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:
- We create a new context with JavaScript as the only permitted language.
- Next, we load the JavaScript bindings object and assign it to a local variable
jsBindings
. - Then, we insert a new member
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. - After that, we declare a new global variable in JavaScript and verify that it is accessible as member of the language bindings object.
- Next, we access we access a JavaScript builtin named
Math.abs
symbol and execute it with -42. This result is asserted to be 42. - Finally, we close the context to free all allocated resources.
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 inasValue(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 Context.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 theContext
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 orall 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 Context.Builder.allowValueSharing(boolean)
for details.
Proxies
Theproxy 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 anIllegalStateException
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 theclose(boolean)
method. A context may also be exited
at the guest application request. There are two ways a guest language may exit.
- Soft exit. A guest language throws a special exception that causes the embedder thread to
eventually throw a
PolyglotException
withPolyglotException.isExit()
returningtrue
andPolyglotException.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. - Hard exit. A guest language uses a builtin command that unwinds all context threads and
closes the context by force. Embedder threads also throw a
PolyglotException
withPolyglotException.isExit()
returningtrue
andPolyglotException.getExitStatus()
returning the exit status code specified by the guest application. However, the context is closed automatically. The hard exit can be customized usingContext.Builder.useSystemExit(boolean)
. Iftrue
, the context threads are unwound by callingSystem.exit(int)
with the exit status parameter specified by the guest application. This operation terminates the whole host application.
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 Class Summary
-
Method Summary
Modifier and TypeMethodDescriptionConverts a host value to a polyglotvalue
representation.void
close()
Closes this context and frees up potentially allocated native resources.void
close
(boolean cancelIfExecuting) Closes the context and frees up potentially allocated native resources.static Context
Creates a context with default configuration.void
enter()
Explicitly enters the context on the current thread.boolean
eval
(String languageId, CharSequence source) Evaluates a guest language code literal, using a providedlanguage id
.Evaluates a source object by using the language specified in the source.getBindings
(String languageId) Returns a value that represents the top-most bindings of a language.static Context
Returns the currently entered polyglot context.Provides access to meta-data about the underlying Graal engine.Returns polyglot bindings that may be used to exchange symbols between the host and guest languages.int
hashCode()
boolean
initialize
(String languageId) Forces the initialization of a language.void
Use this method to interrupt this context.void
leave()
Explicitly leaves the context on the current thread.static Context.Builder
newBuilder
(String... permittedLanguages) Creates a builder for constructing a context with custom configuration.parse
(String languageId, CharSequence source) Parses but does not evaluate a guest language code literal using a providedlanguage id
and character sequence and returns avalue
that can beexecuted
.void
Resets all accumulators of resource limits for the associated context to zero.void
Polls safepoints events and executes them for the current thread.
-
Method Details
-
getEngine
Provides access to meta-data about the underlying Graal engine.- Returns:
- Graal
Engine
being used by this context - Since:
- 19.0
-
eval
Evaluates a source object by using the language specified in the source. The result is accessible asvalue
and never returnsnull
. The first time a source is evaluated, it will be parsed. Consecutive invocations of eval with the same source will only execute the already parsed code.Basic Example:
try (Context context = Context.create()) { Source source = Source.newBuilder("js", "42", "mysource.js").build(); Value result = context.eval(source); assert result.asInt() == 42; }
- Parameters:
source
- a source object to evaluate- Returns:
- the evaluation result. The returned instance is never
null
, but the result might represent anull
value. - Throws:
PolyglotException
- in case the guest language code parsing or evaluation failed.IllegalStateException
- if the context is already closed and the current thread is not allowed to access it.IllegalArgumentException
- if the language of the given source is not installed or theMIME type
is not supported with the language.- Since:
- 19.0
-
eval
Evaluates a guest language code literal, using a providedlanguage id
. The result is accessible asvalue
and never returnsnull
. The providedCharSequence
must represent an immutable String.Basic Example:
try (Context context = Context.create()) { Value result = context.eval("js", "42"); assert result.asInt() == 42; }
- Returns:
- the evaluation result. The returned instance is never
null
, but the result might represent anull
value. - Throws:
PolyglotException
- in case the guest language code parsing or evaluation failed.IllegalArgumentException
- if the language does not exist or is not accessible.IllegalStateException
- if the context is already closed and the current thread is not allowed to access it, or if the given language is not installed.- Since:
- 19.0
-
parse
Parses but does not evaluate a given source by using the language specified in the source and returns avalue
that can beexecuted
. If a parsing fails, e.g. due to a syntax error in the source, then aPolyglotException
will be thrown. In case of a syntax error thePolyglotException.isSyntaxError()
will returntrue
. There is no guarantee that only syntax errors will be thrown by this method. Any other guest language exception might be thrown. If the validation succeeds then the method completes without throwing an exception.The result value only supports an empty set of arguments to
execute
. If executed repeatedly then the source is evaluated multiple times.Interactive
sources will print their result for each execution of the parsing result to theoutput
stream.If the parsing succeeds and the source is
cached
then the result will automatically be reused for consecutive calls toparse(Source)
oreval(Source)
. If the validation should be performed for each invocation or the result should not be remembered thencached
can be set tofalse
. By default sources are cached.Basic Example:
try (Context context = Context.create()) { Source source = Source.create("js", "42"); Value value; try { value = context.parse(source); // parsing succeeded } catch (PolyglotException e) { if (e.isSyntaxError()) { SourceSection location = e.getSourceLocation(); // syntax error detected at location } else { // other guest error detected } throw e; } // evaluate the parsed script value.execute(); }
- Parameters:
source
- a source object to parse- Throws:
PolyglotException
- in case the guest language code parsing or validation failed.IllegalArgumentException
- if the language does not exist or is not accessible.IllegalStateException
- if the context is already closed and the current thread is not allowed to access it, or if the given language is not installed.- Since:
- 20.2
-
parse
Parses but does not evaluate a guest language code literal using a providedlanguage id
and character sequence and returns avalue
that can beexecuted
. The providedCharSequence
must represent an immutable String. This method represents a short-hand forparse(Source)
.The result value only supports an empty set of arguments to
execute
. If executed repeatedly then the source is evaluated multiple times.Interactive
sources will print their result for each execution of the parsing result to theoutput
stream.try (Context context = Context.create()) { Value value; try { value = context.parse("js", "42"); // parsing succeeded } catch (PolyglotException e) { if (e.isSyntaxError()) { SourceSection location = e.getSourceLocation(); // syntax error detected at location } else { // other guest error detected } throw e; } // evaluate the parsed script value.execute(); }
- Throws:
PolyglotException
- in case the guest language code parsing or evaluation failed.IllegalArgumentException
- if the language does not exist or is not accessible.IllegalStateException
- if the context is already closed and the current thread is not allowed to access it, or if the given language is not installed.- Since:
- 20.2
-
getPolyglotBindings
Returns polyglot bindings that may be used to exchange symbols between the host and guest languages. All languages have unrestricted access to the polyglot bindings. The returned bindings object always hasmembers
and its members arereadable
,writable
andremovable
.Guest languages may put and get members through language specific APIs. For example, in JavaScript, symbols of the polyglot bindings can be accessed using
Polyglot.import("name")
and set usingPolyglot.export("name", value)
. Please see the individual language reference on how to access these symbols.- Throws:
IllegalStateException
- if context is already closed.- Since:
- 19.0
-
getBindings
Returns a value that represents the top-most bindings of a language. The top most bindings of the language returns amember
for a symbol in the scope. Languages may allow modifications of members of the returned bindings object at the language's discretion. If the language has not beeninitialized
yet, it will be initialized when the bindings are requested.- Throws:
IllegalArgumentException
- if the language does not exist or is not accessible.IllegalStateException
- if the context is already closed.PolyglotException
- in case the lazy initialization failed due to a guest language error.- Since:
- 19.0
-
initialize
Forces the initialization of a language. It is not necessary to explicitly initialize a language, it will be initialized the first time it is used.- Parameters:
languageId
- the identifier of the language to initialize.- Returns:
true
if the language was initialized. Returnsfalse
if it was already initialized.- Throws:
PolyglotException
- in case the initialization failed due to a guest language error.IllegalArgumentException
- if the language does not exist or is not accessible.IllegalStateException
- if the context is already closed.- Since:
- 19.0
-
resetLimits
public void resetLimits()Resets all accumulators of resource limits for the associated context to zero.- Since:
- 19.3
-
asValue
Converts a host value to a polyglotvalue
representation. This conversion is applied implicitly wheneverexecution
orinstantiation
arguments are provided,members
andarray elements
are set or when a value is returned by apolyglot proxy
. It is not required nor efficient to explicitly convert to polyglot values before performing these operations. This method is useful to convert amapped
host value back to a polyglot value while preserving the identity.When a host value is converted to a polyglot value the following rules apply:
- If the
hostValue
isnull
, then it will be interpreted as polyglotnull
. - If the
hostValue
is already apolyglot value
, then it will be cast toValue
. - If the
hostValue
is an instance ofByte
,Short
,Integer
,Long
,Float
orDouble
, then it will be interpreted as polyglotnumber
. Other subclasses ofNumber
will be interpreted ashost object
(see later). - If the
hostValue
is an instance ofCharacter
orString
, then it will be interpreted as polyglotstring
. - If the
hostValue
is an instance ofBoolean
, then it will be interpreted as polyglotboolean
. - If the
hostValue
is an instance ofInstant
,LocalTime
,ZonedDateTime
,Date
but notDate
orTime
then it will be interpreted as polyglottime
. - If the
hostValue
is an instance ofInstant
,LocalDate
,ZonedDateTime
,Date
but notTime
orDate
then it will be interpreted as polyglotdate
. - If the
hostValue
is an instance ofZoneId
,Instant
,ZonedDateTime
,Date
but notTime
andDate
then it will be interpreted as polyglottime zone
. - If the
hostValue
is an instance ofZonedDateTime
,Instant
,ZonedDateTime
,Date
but notTime
andDate
then it will be interpreted as polyglotinstant
. - If the
hostValue
is an instance ofDuration
then it will be interpreted as polyglotduration
. - If the
hostValue
is apolyglot proxy
, then it will be interpreted according to the behavior specified by the proxy. See the javadoc of the proxy subclass for further details. - If the
hostValue
is a non-primitivemapped Java value
, then the original value will be restored. For example, if a guest language object was mapped toMap
, then the original object identity will be preserved when converting back to a polyglot value. - Any other
hostValue
will be interpreted ashost object
. Host objects expose all their public java fields and methods asmembers
. In addition, Java arrays, subtypes ofList
andMap.Entry
will be interpreted as a value witharray elements
. The subtypes ofIterable
will be interpreted as a value withValue.hasIterator()
iterator}. The subtypes ofIterator
will be interpreted as aniterator
value. The subtypes ofMap
will be interpreted as a value withValue.hasHashEntries()
hash entries}. And single method interfaces annotated withFunctionalInterface
areexecutable
directly. JavaClass
instances are interpreted asinstantiable
, but they do not expose Class methods as members.
Basic Examples: The following assertion statements always hold:
Context context = Context.create(); assert context.asValue(null).isNull(); assert context.asValue(42).isNumber(); assert context.asValue("42").isString(); assert context.asValue('c').isString(); assert context.asValue(new String[0]).hasArrayElements(); assert context.asValue(new ArrayList<>()).isHostObject(); assert context.asValue(new ArrayList<>()).hasArrayElements(); assert context.asValue((Supplier<Integer>) () -> 42).execute().asInt() == 42;
Mapping to Java methods and fields
When Java host objects are passed to guest languages, their public methods and fields are provided asmembers
. Methods and fields are grouped by name, so only one member is exposed for each name.Class
objects have a member namedstatic
referring to the class's companion object containing the static methods of the class. Likewise, the companion object has a member namedclass
that points back to the class object.When an argument value needs to be mapped to match a required Java method parameter type, then the semantics of
host value mapping
is used. The result of the mapping is equivalent of callingValue.as(Class)
with the parameter type. Therefore, aClassCastException
orNullPointerException
is thrown if a parameter value cannot be cast to the required parameter type.Overloaded java methods are selected based on the provided arguments. In case multiple mapped Java methods with the same name are applicable for
executions
orinstantiations
, then the method with the most concrete method with applicable arguments will be called.The following parameter type hierarchy is used for a method resolution. Left-most parameter types are prioritized over types to their right.
Boolean
values: boolean, Boolean, Object- String values: char, Character, String, CharSequence, Object
- Number values: byte, Byte, short, Short, int, Integer, long, Long, float, Float, double, Double, Number, Object
- Other values are resolved based on their Java type hierarchy.
Advanced Example: This example first creates a new instance of the Java class
Record
and inspects it using the polyglot value API. Later, a host value is converted to a polyglot value using JavaScript guest language.In the following examples all assertions hold.
class JavaRecord { public int x = 42; public double y = 42.0; public String name() { return "foo"; } } Context context = Context.create(); Value record = context.asValue(new JavaRecord()); assert record.getMember("x").asInt() == 42; assert record.getMember("y").asDouble() == 42.0d; assert record.getMember("name").execute().asString().equals("foo"); assert context.eval("js", "(function(record) record.x)") .execute(record).asInt() == 42; assert context.eval("js", "(function(record) record.y)") .execute(record).asDouble() == 42.0d; assert context.eval("js", "(function(record) record.name())") .execute(record).asString().equals("foo");
- Parameters:
hostValue
- the host value to convert to a polyglot value.- Returns:
- the polyglot value.
- Throws:
IllegalStateException
- if the context is already closed- Since:
- 19.0
- See Also:
- If the
-
enter
public void enter()Explicitly enters the context on the current thread. A context needs to be entered and left for any operation to be performed. For example, before and after invoking theexecute
method. This can be inefficient if a very high number of simple operations needs to be performed. Byentering
andleaving
once explicitly, the overhead for entering/leaving the context for each operation can be eliminated. Contexts can be entered multiple times on the same thread.- Throws:
IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a language has denied execution on the current thread.- Since:
- 19.0
- See Also:
-
equals
-
hashCode
public int hashCode() -
leave
public void leave()Explicitly leaves the context on the current thread. The context must beentered
before calling this method.- Throws:
IllegalStateException
- if the context is already closed or if the context was notentered
on the current thread.- Since:
- 19.0
- See Also:
-
close
public void close(boolean cancelIfExecuting) Closes the context and frees up potentially allocated native resources. A context cannot free all native resources allocated automatically. For this reason it is necessary to close contexts after use. If a context is cancelled, then the executing thread will throw aPolyglotException
. The exception indicates that it wascancelled
. Please note, canceling a single context can negatively affect the performance of other executing contexts constructed with the same engine.If internal errors occur during context closing, then they are printed to the configured
error output stream
. If a context was closed, then its methods will throw anIllegalStateException
when invoked. If an attempt to close a context was successful, then consecutive calls to close have no effect.For convenience, before the actual closing process begins, the close method leaves the context on the current thread, if it was entered
explicitly
.- Parameters:
cancelIfExecuting
- iftrue
then currently executing contexts will becancelled
, else anIllegalStateException
is thrown.- Throws:
PolyglotException
- in case the close failed due to a guest language error, or, if cancelIfExecuting isfalse
, the exception is also thrown when the context wascancelled
or the context wasexited
at request of the guest application.IllegalStateException
- if the context is still running and cancelIfExecuting isfalse
- Since:
- 19.0
- See Also:
-
close
public void close()Closes this context and frees up potentially allocated native resources. A context may not free all native resources allocated automatically. For this reason it is recommended to close contexts after use. If the context is currently being executed on another thread, then anIllegalStateException
is thrown. To close concurrently executing contexts seeclose(boolean)
.If internal errors occur during the context closure, then they are printed to the configured
error output stream
. If a context was closed, then its methods will throw anIllegalStateException
, when invoked. If an attempt to close a context was successful, then consecutive calls to close have no effect.For convenience, before the actual closing process begins, the close method leaves the context on the current thread, if it was entered
explicitly
.- Specified by:
close
in interfaceAutoCloseable
- Throws:
PolyglotException
- in case the close failed due to a guest language error, or the context wascancelled
or the context wasexited
at request of the guest application.IllegalStateException
- if the context is currently executing on another thread.- Since:
- 19.0
- See Also:
-
interrupt
Use this method to interrupt this context. The interruption is non-destructive meaning the context is still usable after this method finishes. Please note that guest finally blocks are executed during interrupt. A context thread may not be interruptiple if it uses non-interruptible waiting or executes non-interruptible host code. This method may be used as a "soft cancel", meaning that it can be used beforeclose(true)
is executed.- Parameters:
timeout
- specifies the duration the interrupt method will wait for the active threads of the context to be finished. Setting the duration to0
means wait indefinitely.- Throws:
IllegalStateException
- in case the context is entered in the current thread.TimeoutException
- in case the interrupt was not successful, i.e., not all threads were finished within the specified time limit.- Since:
- 20.3
-
safepoint
public void safepoint()Polls safepoints events and executes them for the current thread. This allows guest languages to run actions between long-running host method calls. Polyglot embeddings that rely on cancellation should call this method whenever a potentially long-running host operation is executed. For example, iterating an unbounded array. Guest language code and operations automatically poll safepoints regularly.In this example we allow
interruption
andcancellation
to stop the processing of our event queue.class EventProcessor { List
- Throws:
PolyglotException
- in case the close failed due to a guest language error.IllegalStateException
- if the context is alreadyclosed
.- Since:
- 21.1
-
getCurrent
Returns the currently entered polyglot context. A context will be entered if the current executing Java method is called by a Graal guest language or if a context is entered explicitly usingenter()
on the current thread. The returned context may be used to:- Evaluate guest language code from
string literals
orfile
sources. Convert
Java values topolyglot values
.- Access top-level
bindings
of other languages. - Access
polyglot bindings
. - Access meta-data like available
languages
oroptions
of theengine
.
The returned context can not be used to
enter
,leave
orclose
the context orengine
. Invoking such methods will cause anIllegalStateException
to be thrown. This ensures that only thecreator
of a context is allowed to enter, leave or close a context.The current entered context may change. It is therefore required to call
getCurrent
every time a context is needed. The current entered context should not be cached in static fields.- Throws:
IllegalStateException
- if no context is currently entered.- Since:
- 19.0
- Evaluate guest language code from
-
create
Creates a context with default configuration. This method is a shortcut fornewBuilder(permittedLanuages).build()
.- Since:
- 19.0
- See Also:
-
newBuilder
Creates a builder for constructing a context with custom configuration.- Parameters:
permittedLanguages
- names of languages permitted in the context. If no languages are provided, then all installed languages will be permitted. If an explicitengine
was specified then only those languages may be used that were installed andpermitted
by the specified engine. Languages are validated when the context isbuilt
. AnIllegalArgumentException
will be thrown if an unknown or a language denied by the engine was used.- Returns:
- a builder that can create a context
- Since:
- 19.0
-