Class TruffleLanguage.Env
- Enclosing class:
TruffleLanguage<C>
TruffleLanguage
. Each active
TruffleLanguage
receives instance of the environment before any code is executed upon
it. The environment has knowledge of all active languages and can exchange symbols between
them.- Since:
- 0.8 or earlier
-
Method Summary
Modifier and TypeMethodDescriptionvoid
addToHostClassPath
(TruffleFile entry) Adds an entry to the Java host class loader.asBoxedGuestValue
(Object guestObject) Wraps primitive interop values in a TruffleObject exposing their methods as members.asGuestValue
(Object hostObject) Converts a existing Java host object to a guest language value.asHostException
(Throwable exception) Unwraps a host exception thrown by a Java method invocation.asHostObject
(Object value) Returns the java host representation of a Truffle guest object if it represents a Java host language object.asHostSymbol
(Class<?> symbolClass) Converts a Java class to a host symbol as if bylookupHostSymbol(symbolClass.getName())
but without an actual lookup.createHostAdapter
(Object[] types) Creates a Java host adapter class that can be instantiated with a guest object (as the last argument) in order to create adapter instances of the provided host types, (non-final) methods of which delegate to the guest object's invocable members.createHostAdapterClass
(Class<?>[] types) Deprecated.createHostAdapterClassWithStaticOverrides
(Class<?>[] types, Object classOverrides) Deprecated.since 22.1; replaced bycreateHostAdapterWithClassOverrides(Object[], Object)
.createHostAdapterWithClassOverrides
(Object[] types, Object classOverrides) LikecreateHostAdapter(Object[])
but creates a Java host adapter class with class-level overrides, i.e., the guest object provided asclassOverrides
is statically bound to the class rather than instances of the class.createSystemThread
(Runnable runnable) Creates a new thread designed to process language internal tasks in the background.createSystemThread
(Runnable runnable, ThreadGroup threadGroup) Creates a new thread designed to process language internal tasks in the background.createTempDirectory
(TruffleFile dir, String prefix, FileAttribute<?>... attrs) Creates a new directory in the specified or default temporary directory, using the given prefix to generate its name.createTempFile
(TruffleFile dir, String prefix, String suffix, FileAttribute<?>... attrs) Creates a new empty file in the specified or default temporary directory, using the given prefix and suffix to generate its name.createThread
(Runnable runnable) Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.createThread
(Runnable runnable, TruffleContext context) Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.createThread
(Runnable runnable, TruffleContext context, ThreadGroup group) Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.createThread
(Runnable runnable, TruffleContext context, ThreadGroup group, long stackSize) Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.err()
Standard error writer provided byContext.Builder.err(OutputStream)
this language is being executed in.void
exportSymbol
(String symbolName, Object value) Explicitly exports a symbol to the polyglot bindings object.findMetaObject
(Object value) Find a metaobject of a value, if any.String[]
Returns the application arguments that were provided for this context.Configuration arguments passed from an outer language context to an inner language context.Returns the polyglot context associated with this environment.Gets the current working directory.Returns an unmodifiable map of the process environment.Returns the name separator used to separate names inTruffleFile
's path string.Retrieves the host language used in this environment.Returns a map instrument-id to instrument instance of all instruments that are installed in the environment.Returns all languages that are installed and internally accessible in the environment.getInternalResource
(Class<? extends InternalResource> resource) Returns theTruffleFile
representing the target directory of an internal resource.getInternalResource
(String resourceId) Returns theTruffleFile
representing the target directory of an internal resource.getInternalTruffleFile
(String path) Returns aTruffleFile
for given path.ReturnsTruffleFile
for givenURI
.getLanguageInfo
(Class<? extends TruffleLanguage<?>> languageClass) Returns thelanguage info
for a given language class if available.Find or create a context-bound logger.Find or create a context-bound logger.Returns option values for the options described inTruffleLanguage.getOptionDescriptors()
.Returns the path separator used to separate filenames in a path list.Returns a TruffleObject that represents the polyglot bindings.Returns all languages that are installed and publicly accessible in the environment.getPublicTruffleFile
(String path) Returns aTruffleFile
for given path.getPublicTruffleFile
(URI uri) Returns aTruffleFile
for given path.Returns the context'sSandboxPolicy
.getScopeInternal
(LanguageInfo language) Returns the scope object of a non-nullinternal language
.getScopePublic
(LanguageInfo language) Returns the scope object of a non-nullpublic language
.Returns the default time zone of this environment.getTruffleFileInternal
(String path, Predicate<TruffleFile> filter) Returns aTruffleFile
for the given path.getTruffleFileInternal
(URI uri, Predicate<TruffleFile> filter) Returns aTruffleFile
for given URI.importSymbol
(String symbolName) Explicitly imports a symbol from the polyglot bindings.in()
Input stream provided byContext.Builder.in(InputStream)
this language is being executed in.boolean
initializeLanguage
(LanguageInfo targetLanguage) Ensures that the target language is initialized.boolean
Returnstrue
if the creation of a sub-process is allowed in the current environment.boolean
Returnstrue
if the creation of new threads is allowed in the current environment.boolean
Returnstrue
if access to files is allowed, elsefalse
.boolean
isHostException
(Throwable exception) Tests whether an exception is a host exception thrown by a Java Interop method invocation.boolean
isHostFunction
(Object value) Returnstrue
if the argument is a Java host language function wrapped using Truffle interop.boolean
Returnstrue
if host access is generally allowed.boolean
isHostObject
(Object value) Returnstrue
if the argument is Java host language object wrapped using Truffle interop.boolean
isHostSymbol
(Object guestObject) Returnstrue
if the argument is a host symbol, representing the constructor and static members of a Java class, as obtained by e.g.boolean
Returnstrue
if context options are allowed to be modified for inner contexts, orfalse
if not.boolean
Deprecated.since 23.0; replaced byisFileIOAllowed()
.boolean
isMimeTypeSupported
(String mimeType) Allows it to be determined if thisContext
can execute code written in a language with a given MIME type.boolean
Returnstrue
if access to native code is generally allowed.boolean
Returnstrue
if polyglot bindings access is allowed, elsefalse
.boolean
Deprecated.in 24.1 useisPolyglotEvalAllowed(null) instead
.boolean
isPolyglotEvalAllowed
(LanguageInfo targetLanguage) Returnstrue
if the current language is allowed to evaluate guest application provided code of the given language, elsefalse
.boolean
Returnstrue
if thisContext
is being pre-initialized.boolean
Returnstrue
if access to network sockets is allowed, elsefalse
.<S> S
lookup
(InstrumentInfo instrument, Class<S> type) Returns an additional service provided by this instrument, specified by type.<S> S
lookup
(LanguageInfo language, Class<S> type) Returns an additional service provided by the given language, specified by type.<T> T
Looks additional service up.lookupHostSymbol
(String symbolName) Looks up a Java class in the top-most scope the host environment.Deprecated.usenewInnerContextBuilder(String...)
instead.newInnerContextBuilder
(String... permittedLanguages) Returns a new context builder useful to create inner context instances.newProcessBuilder
(String... command) Creates a new process builder with the specified operating program and arguments.newTruffleThreadBuilder
(Runnable runnable) Creates a builder for threads that have access to the given context.out()
Standard output writer provided byContext.Builder.out(OutputStream)
this language is being executed in.parseInternal
(Source source, String... argumentNames) Parses the source of a public or internal language and returns the parse result asCallTarget
.parsePublic
(Source source, String... argumentNames) Parses the source of a public language and returns the parse result asCallTarget
.void
registerOnDispose
(Closeable closeable) RegistersCloseable
for automatic close on context dispose.void
registerService
(Object service) Registers additional services provided by the language.void
setCurrentWorkingDirectory
(TruffleFile currentWorkingDirectory) Sets the current working directory.submitThreadLocal
(Thread[] threads, ThreadLocalAction action) Submits a thread local action to be performed at the next guest language safepoint on a provided set of threads, once for each thread.
-
Method Details
-
getOptions
Returns option values for the options described inTruffleLanguage.getOptionDescriptors()
. The returned options are nevernull
.- Since:
- 0.27
-
getApplicationArguments
Returns the application arguments that were provided for this context. The arguments array and its elements are nevernull
. It is up to the language implementation whether and how they are accessible within the guest language scripts.- Since:
- 0.27
-
isCreateThreadAllowed
public boolean isCreateThreadAllowed()Returnstrue
if the creation of new threads is allowed in the current environment.- Since:
- 0.28
- See Also:
-
createThread
Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.Creates a new thread that has access to the current language context. SeecreateThread(Runnable, TruffleContext, ThreadGroup, long)
for a detailed description of the parameters. Thegroup
is null andstackSize
set to 0.- Since:
- 0.28
-
createThread
Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.Creates a new thread that has access to the given context. SeecreateThread(Runnable, TruffleContext, ThreadGroup, long)
for a detailed description of the parameters. Thegroup
is null andstackSize
set to 0.- Since:
- 0.28
- See Also:
-
createThread
@Deprecated public Thread createThread(Runnable runnable, TruffleContext context, ThreadGroup group) Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.Creates a new thread that has access to the given context. SeecreateThread(Runnable, TruffleContext, ThreadGroup, long)
for a detailed description of the parameters. ThestackSize
set to 0.- Since:
- 0.28
- See Also:
-
createThread
@Deprecated public Thread createThread(Runnable runnable, TruffleContext context, ThreadGroup group, long stackSize) Deprecated.UsenewTruffleThreadBuilder(Runnable)
instead.Creates a new thread that has access to the given context. A thread isinitialized
when it isstarted
anddisposed
as soon as the thread finished the execution.It is recommended to set an
uncaught exception handler
for the created thread. For example the thread can throw an uncaught exception if one of the initialized language contexts don't support execution on this thread.The language that created and started the thread is responsible to stop and join it during the
finalizeContext
, otherwise anAssertionError
is thrown. It's not safe to use theExecutorService.awaitTermination(long, java.util.concurrent.TimeUnit)
to detect Thread termination as the polyglot thread may be cancelled before executing the executor worker.
A typical implementation looks like:class AsyncThreadLanguage extends TruffleLanguage<Context> { @Override protected Context createContext(Env env) { return new Context(env); } @Override protected boolean isThreadAccessAllowed(Thread thread, boolean singleThreaded) { // allow access from any thread instead of just one return true; } @Override protected void initializeContext(Context context) throws Exception { // create and start a Thread for the asynchronous task // remeber the Thread reference to stop and join it in // the finalizeContext Thread t = context.env.newTruffleThreadBuilder(new Runnable() { @Override public void run() { // asynchronous task } }).build(); context.startedThreads.add(t); t.start(); } @Override protected void finalizeContext(Context context) { // stop and join all the created Threads boolean interrupted = false; for (int i = 0; i < context.startedThreads.size();) { Thread threadToJoin = context.startedThreads.get(i); try { if (threadToJoin != Thread.currentThread()) { threadToJoin.interrupt(); threadToJoin.join(); } i++; } catch (InterruptedException ie) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } }
The
TruffleContext
can be either an inner context created bynewInnerContextBuilder(String...)
.build()
, or the context associated with this environment obtained fromgetContext()
.- Parameters:
runnable
- the runnable to run on this thread.context
- the context to enter and leave when the thread is started.group
- the thread group, passed on to the underlyingThread
.stackSize
- the desired stack size for the new thread, or zero if this parameter is to be ignored.- Throws:
IllegalStateException
- if thread creation is notallowed
.- Since:
- 0.28
- See Also:
-
newTruffleThreadBuilder
Creates a builder for threads that have access to the given context.- Parameters:
runnable
- the runnable to run on the threads created by the builder.- Returns:
- the builder for threads that have access to the given context.
- Since:
- 23.0
-
createSystemThread
Creates a new thread designed to process language internal tasks in the background. SeecreateSystemThread(Runnable, ThreadGroup)
for a detailed description of the parameters.- Since:
- 22.3
- See Also:
-
createSystemThread
Creates a new thread designed to process language internal tasks in the background. The created thread cannot enter the context, if it tries anIllegalStateException
is thrown. Creating or terminating a system thread does not notifylanguages
or instruments' thread-listeners. Creating a system thread does not cause a transition to multi-threaded access. Thecreation permit
is not required to create a system thread, but the caller must be entered in a context to create a system thread, if not anIllegalStateException
is thrown.It is recommended to set an
uncaught exception handler
for the created thread. For example the thread can throw an uncaught exception if the context is closed before the thread is started.The language that created and started the thread is responsible to stop and join it during the
TruffleLanguage.disposeContext(Object)
disposeContext}, otherwise anIllegalStateException
is thrown. It's not safe to use theExecutorService.awaitTermination(long, java.util.concurrent.TimeUnit)
to detect Thread termination as the system thread may be cancelled before executing the executor worker.
A typical implementation looks like:class SystemThreadLanguage extends TruffleLanguage<SystemThreadLanguage.Context> { static class Context { private final BlockingQueue<Runnable> tasks; private final Env env; private volatile Thread systemThread; private volatile boolean cancelled; Context(Env env) { this.tasks = new LinkedBlockingQueue<>(); this.env = env; } } @Override protected Context createContext(Env env) { return new Context(env); } @Override protected void initializeContext(Context context) { // Create and start a Thread for the asynchronous internal task. // Remember the Thread to stop and join it in the disposeContext. context.systemThread = context.env.createSystemThread(() -> { while (!context.cancelled) { try { Runnable task = context.tasks. poll(Integer.MAX_VALUE, SECONDS); if (task != null) { task.run(); } } catch (InterruptedException ie) { // pass to cancelled check } } }); context.systemThread.start(); } @Override protected void disposeContext(Context context) { // Stop and join system thread. context.cancelled = true; Thread threadToJoin = context.systemThread; if (threadToJoin != null) { threadToJoin.interrupt(); boolean interrupted = false; boolean terminated = false; while (!terminated) { try { threadToJoin.join(); terminated = true; } catch (InterruptedException ie) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } } }
- Parameters:
runnable
- the runnable to run on this thread.threadGroup
- the thread group, passed on to the underlyingThread
.- Throws:
IllegalStateException
- if the context is already closed.- Since:
- 22.3
- See Also:
-
newContextBuilder
Deprecated.usenewInnerContextBuilder(String...)
instead. Note that the replacement method configures the context differently by default. To restore the old behavior:newInnerContextBuilder() .initializeCreatorContext(true).inheritAllAccess(true).build()
Returns a new context builder useful to create inner context instances.- Since:
- 0.27
- See Also:
-
newInnerContextBuilder
Returns a new context builder useful to create inner context instances.By default the inner context inherits none of the access privileges. To inherit access set
TruffleContext.Builder.inheritAllAccess(boolean)
totrue
.No language context will be initialized by default in the inner context. In order to initialize the creator context use
TruffleContext.Builder.initializeCreatorContext(boolean)
, initialize the language after context creation usingTruffleContext.initializePublic(Node, String)
or evaluate a source usingTruffleContext.evalPublic(Node, Source)
.- Parameters:
permittedLanguages
- ids of languages permitted in the context. If no languages are provided, then all languages permitted to the outer context will be permitted. Languages are validated when the context isbuilt
. AnIllegalArgumentException
will be thrown if an unknown or a language denied by the engine was used.- Since:
- 22.3
- See Also:
-
getPolyglotBindings
Returns a TruffleObject that represents the polyglot bindings. The polyglot bindings consists of a set of symbols that have been exported explicitly by the languages or the embedder. This set of symbols allows for data exchange between polyglot languages. The polyglot bindings is separate from language bindings. The symbols can by read using string identifiers, a list of symbols may be requested with the keys message. Existing identifiers are removable, modifiable, readable and any new identifiers are insertable.- Throws:
SecurityException
- if polyglot access is not enabled- Since:
- 0.32
- See Also:
-
importSymbol
Explicitly imports a symbol from the polyglot bindings. The behavior of this method is equivalent to sending a READ message to thepolyglot bindings
object. Reading a symbol that does not exist will returnnull
.The returned symbol value can either be a
TruffleObject
(e.g. a native object from the other language) to support interoperability between languages,String
or one of the Java primitive wrappers (Integer
,Double
,Byte
,Boolean
, etc.).Polyglot symbols can only be imported if the
polyglot bindings access
is allowed.- Parameters:
symbolName
- the name of the symbol to search for- Returns:
- object representing the symbol or
null
if it does not exist - Throws:
SecurityException
- if importing polyglot symbols is not allowed- Since:
- 0.8 or earlier
-
exportSymbol
Explicitly exports a symbol to the polyglot bindings object. The behavior of this method is equivalent to sending a WRITE message to thepolyglot bindings
object. Exporting a symbol with anull
value will remove the symbol from the polyglot object.The exported symbol value can either be a
TruffleObject
(e.g. a native object from the other language) to support interoperability between languages,String
or one of the Java primitive wrappers (Integer
,Double
,Byte
,Boolean
, etc.).Polyglot symbols can only be export if the
polyglot bindings access
is allowed.- Parameters:
symbolName
- the name with which the symbol should be exported into the polyglot scopevalue
- the value to export for- Throws:
SecurityException
- if exporting polyglot symbols is not allowed- Since:
- 0.27
-
isHostLookupAllowed
public boolean isHostLookupAllowed()Returnstrue
if host access is generally allowed. If this method returnsfalse
thenlookupHostSymbol(String)
will always fail. Host lookup is generally disallowed if the embedder provided a nullhost class filter
.- Since:
- 0.27
-
addToHostClassPath
Adds an entry to the Java host class loader. All classes looked up withlookupHostSymbol(String)
will lookup classes with this new entry. If the entry was already added then calling this method again for the same entry has no effect. Given entry must not benull
.Note that classes added by this method are in the unnamed module.
- Throws:
SecurityException
- if the file is notreadable
.- Since:
- 19.0
-
lookupHostSymbol
Looks up a Java class in the top-most scope the host environment. Throws an error if no symbol was found or the symbol was not accessible. Symbols might not be accessible if ahost class filter
prevents access. The returned object is always aTruffleObject
that represents the class symbol.- Parameters:
symbolName
- the qualified class name in the host language.- Since:
- 0.27
-
isHostObject
Returnstrue
if the argument is Java host language object wrapped using Truffle interop.- Since:
- 19.0
- See Also:
-
asHostObject
Returns the java host representation of a Truffle guest object if it represents a Java host language object. ThrowsClassCastException
if the provided argument is not ahost object
.- Since:
- 19.0
-
asGuestValue
Converts a existing Java host object to a guest language value. If the value is already an interop value, then no conversion will be performed. Otherwise, the returned wraps the host object and provides support for the interop contract to access the java members. The interpretation of converted objects is described inContext.asValue(Object)
.This method should be used exclusively to convert already allocated Java objects to a guest language representation. To allocate new host objects users should use
lookupHostSymbol(String)
to lookup the class and then send a NEW interop message to that object to instantiate it. This method does not respect configuredclass filters
.- Parameters:
hostObject
- the host object to convert- Since:
- 19.0
-
asBoxedGuestValue
Wraps primitive interop values in a TruffleObject exposing their methods as members. By default primitive host values are not wrapped in TruffleObjects to expose their members. This method is intended for compatibility with existing Java interop APIs that expect such behavior. This method boxes the following primitive interop values:Boolean
,Byte
,Short
,Integer
,Long
,Float
,Double
,Character
,String
. If the provided value is already boxed then the current value will be returned. If the provided value is not an interop value then anIllegalArgumentException
will be thrown.- Parameters:
guestObject
- the primitive guest value to box- Throws:
IllegalArgumentException
- if value is an invalid interop value.- Since:
- 19.0
- See Also:
-
isHostFunction
Returnstrue
if the argument is a Java host language function wrapped using Truffle interop.- Since:
- 19.0
-
findMetaObject
Find a metaobject of a value, if any. The metaobject represents a description of the object, reveals it's kind and it's features. Some information that a metaobject might define includes the base object's type, interface, class, methods, attributes, etc.When no metaobject is known, returns
null
. The metaobject is an interop value. An interop value can be either aTruffleObject
(e.g. a native object from the other language) to support interoperability between languages or aString
.- Parameters:
value
- the value to find the meta object for.- Since:
- 19.0
-
isHostException
Tests whether an exception is a host exception thrown by a Java Interop method invocation. Host exceptions may be thrown by interoperability messages. The host exception may be unwrapped usingasHostException(Throwable)
.- Parameters:
exception
- theThrowable
to test- Returns:
true
if theexception
is a host exception,false
otherwise- Since:
- 19.0
- See Also:
-
asHostException
Unwraps a host exception thrown by a Java method invocation. Host exceptions may be thrown by interoperability messages. The host exception may be unwrapped usingasHostException(Throwable)
.- Parameters:
exception
- the host exception to unwrap- Returns:
- the original Java exception
- Throws:
IllegalArgumentException
- if theexception
is not a host exception- Since:
- 19.0
- See Also:
-
isHostSymbol
Returnstrue
if the argument is a host symbol, representing the constructor and static members of a Java class, as obtained by e.g.lookupHostSymbol(java.lang.String)
.- Since:
- 19.0
- See Also:
-
asHostSymbol
Converts a Java class to a host symbol as if bylookupHostSymbol(symbolClass.getName())
but without an actual lookup. Must not be used with Truffle or guest language classes.- Since:
- 19.0
- See Also:
-
isInnerContextOptionsAllowed
public boolean isInnerContextOptionsAllowed()Returnstrue
if context options are allowed to be modified for inner contexts, orfalse
if not. This method only indicates whether the embedder granted wildcard all access for new privileges usingContext.Builder.allowInnerContextOptions(boolean)
.This method is useful to find out whether it is possible to specify options for inner contexts using
TruffleContext.Builder.option(String, String)
, as options can only be specified with all access enabled.- Since:
- 22.3
- See Also:
-
isIOAllowed
Deprecated.since 23.0; replaced byisFileIOAllowed()
.Returnstrue
if access to files is allowed, elsefalse
.- Since:
- 22.3
-
isFileIOAllowed
public boolean isFileIOAllowed()Returnstrue
if access to files is allowed, elsefalse
.- Since:
- 23.0
-
isSocketIOAllowed
public boolean isSocketIOAllowed()Returnstrue
if access to network sockets is allowed, elsefalse
.- Since:
- 23.0
-
isNativeAccessAllowed
public boolean isNativeAccessAllowed()Returnstrue
if access to native code is generally allowed. If this method returnsfalse
then loading native libraries with the Truffle NFI will fail.- Since:
- 19.0
-
isPolyglotEvalAllowed
Deprecated.in 24.1 useisPolyglotEvalAllowed(null) instead
. Note that language implementations should now check whether polyglot eval is allowed also for individual languages, as access could be denied only for an individual language.- Since:
- 19.2
-
isPolyglotEvalAllowed
Returnstrue
if the current language is allowed to evaluate guest application provided code of the given language, elsefalse
. If this method returnstrue
then the current language has permission to useparsePublic(Source, String...)
andgetScopePublic(LanguageInfo)
for the given language. If the given language isnull
then this method will returntrue
if polyglot access is allowed in principle, elsefalse
. Languages may want to call this method twice. Once withnull
to determine whether polyglot eval and scope based builtins should be available to the application at all and once with the concrete language just before the access.The result of this method is safe to be cached per language context, it is guaranteed to not change for a context and target language combination.
- Since:
- 24.1
- See Also:
-
isPolyglotBindingsAccessAllowed
public boolean isPolyglotBindingsAccessAllowed()Returnstrue
if polyglot bindings access is allowed, elsefalse
. Guest languages should hide or disable all polyglot bindings builtins if this flag is set tofalse
. If polyglot bindings access is disabled thengetPolyglotBindings()
,importSymbol(String)
orexportSymbol(String, Object)
fails with a SecurityException.- Since:
- 19.2
- See Also:
-
isMimeTypeSupported
Allows it to be determined if thisContext
can execute code written in a language with a given MIME type.- Returns:
- a boolean that indicates if the MIME type is supported
- Since:
- 0.11
- See Also:
-
parseInternal
Parses the source of a public or internal language and returns the parse result asCallTarget
. Thelanguage id
is used to identify theTruffleLanguage
to use to perform theTruffleLanguage.parse(com.oracle.truffle.api.TruffleLanguage.ParsingRequest)
. The names of arguments are parameters for the resulting {#link CallTarget} that allow thesource
to reference the actual parameters passed toCallTarget.call(java.lang.Object...)
.The suffix
internal
in the method name indicates that the result of this method is not safe to exposed to arbitrary guest code, by default. UseparsePublic(Source, String...)
for that purpose instead. Compared toparsePublic(Source, String...)
this method provides also access tointernal
and dependent languages in addition to public languages. For example, in JavaScript, a call to the eval builtin should forward toparsePublic(Source, String...)
as it contains code provided by the guest language user. Parsing regular expressions with the internal regular expression engine should callparseInternal(Source, String...)
instead, as this is considered an implementation detail of the language.It is recommended that the language uses
parsePublic(Source, String...)
orparseInternal(Source, String...)
instead of directly passing the Source to the parser, in order to support code caching withTruffleLanguage.ContextPolicy.SHARED
andTruffleLanguage.ContextPolicy.REUSE
.- Parameters:
source
- the source to evaluateargumentNames
- the names ofCallTarget.call(java.lang.Object...)
arguments that can be referenced from the source- Returns:
- the call target representing the parsed result
- Throws:
IllegalStateException
- if polyglot context associated with this environment is not entered, or if the language is neither apublic language
nor aninternal language
.IllegalArgumentException
- if the language is not allowed to evaluate code by the current language- Since:
- 19.2
- See Also:
-
parsePublic
Parses the source of a public language and returns the parse result asCallTarget
. Thelanguage id
is used to identify theTruffleLanguage
to use to perform theTruffleLanguage.parse(com.oracle.truffle.api.TruffleLanguage.ParsingRequest)
. The names of arguments are parameters for the resulting {#link CallTarget} that allow thesource
to reference the actual parameters passed toCallTarget.call(java.lang.Object...)
.The suffix
public
in the method name indicates that the result of this method is safe to be exposed by default to guest applications. Public languages are configured by the embedder to be accessible to the guest language program. For example, in JavaScript, a call to the eval builtin should forward toparsePublic(Source, String...)
as it contains code provided by the guest language user. Parsing regular expressions with the internal regular expression engine should callparseInternal(Source, String...)
instead, as this is considered an implementation detail of the language.It is recommended that the language uses
parsePublic(Source, String...)
orparseInternal(Source, String...)
instead of directly passing the Source to the parser, in order to support code caching withTruffleLanguage.ContextPolicy.SHARED
andTruffleLanguage.ContextPolicy.REUSE
.Languages should check for
eval permissions
for eachpublic language
prior to calling this method, otherwiseIllegalArgumentException
is thrown if not sufficient privileges are available.- Parameters:
source
- the source to evaluateargumentNames
- the names ofCallTarget.call(java.lang.Object...)
arguments that can be referenced from the source- Returns:
- the call target representing the parsed result
- Throws:
IllegalStateException
- if polyglot context associated with this environment is not entered, or if the language is not apublic language
IllegalArgumentException
- if the language is not allowed to evaluate code by the current language- Since:
- 19.2
- See Also:
-
in
Input stream provided byContext.Builder.in(InputStream)
this language is being executed in.- Returns:
- reader, never
null
- Since:
- 0.8 or earlier
-
out
Standard output writer provided byContext.Builder.out(OutputStream)
this language is being executed in.- Returns:
- writer, never
null
- Since:
- 0.8 or earlier
-
err
Standard error writer provided byContext.Builder.err(OutputStream)
this language is being executed in.- Returns:
- writer, never
null
- Since:
- 0.8 or earlier
-
lookup
Looks additional service up. An environment for a particularlanguage
may also be associated with additional services. One can request implementations of such services by calling this method with the type identifying the requested service and its API. Services that can be obtained via this method includeInstrumenter
and others.- Type Parameters:
T
- type of requested service- Parameters:
type
- class of requested service- Returns:
- instance of T or
null
if there is no such service available - Since:
- 0.12
-
lookup
Returns an additional service provided by this instrument, specified by type. If an instrument is not enabled, it will be enabled automatically by requesting a supported service. If the instrument does not provide a service for a given type it will not be enabled automatically.- Type Parameters:
S
- the requested type- Parameters:
instrument
- identification of the instrument to querytype
- the class of the requested type- Returns:
- the registered service or
null
if none is found - Since:
- 0.26
-
lookup
Returns an additional service provided by the given language, specified by type. For services registered byTruffleLanguage.Registration.services()
the service lookup will ensure that the language is loaded and services are registered. The provided langauge and type must not benull
.- Type Parameters:
S
- the requested type- Parameters:
language
- the language to querytype
- the class of the requested type- Returns:
- the registered service or
null
if none is found - Since:
- 0.26, 19.0 supports services registered by
registerService
-
initializeLanguage
Ensures that the target language is initialized. This method firstly verifies that the target language is accessible from this language. If not theSecurityException
is thrown. Then the target language initialization is performed if not already done.- Parameters:
targetLanguage
- the language to initialize- Throws:
SecurityException
- if an access totargetLanguage
is not permitted- Since:
- 20.1.0
-
getInternalLanguages
Returns all languages that are installed and internally accessible in the environment. Using the language instance additional services can belooked up
.parseInternal(Source, String...)
is allowed for all languages returned by this method. This list of languages should not be exposed to guest language programs, as it lists internal languages.- Since:
- 19.2
- See Also:
-
getHostLanguage
Retrieves the host language used in this environment. The returned language can be used to obtain the host language top scope object usinggetScopeInternal(LanguageInfo)
method.- Since:
- 24.2
-
getPublicLanguages
Returns all languages that are installed and publicly accessible in the environment. Using the language instance additional services can belooked up
.parsePublic(Source, String...)
is allowed for all languages returned by this method. This list of languages may be exposed ot the guest language program.- Since:
- 19.2
- See Also:
-
getLanguageInfo
Returns thelanguage info
for a given language class if available. The class may be obtained withInteropLibrary.getLanguage(Object)
. Throws anIllegalArgumentException
if the provided language is not registered.- Parameters:
languageClass
- the language class to convert- Returns:
- the associated language info
- Throws:
IllegalArgumentException
- if the language class is not valid.- Since:
- 24.2
-
getInstruments
Returns a map instrument-id to instrument instance of all instruments that are installed in the environment. Using the instrument instance additional services can belooked up
.- Since:
- 0.26
-
getTimeZone
Returns the default time zone of this environment. If the time-zone was not explicitly set by the embedder then thesystem default
time-zone will be returned.- Since:
- 19.2
- See Also:
-
getConfig
Configuration arguments passed from an outer language context to an inner language context. Inner language contexts can be created usingnewInnerContextBuilder(String...)
.- Since:
- 0.11
- See Also:
-
getContext
Returns the polyglot context associated with this environment.- Returns:
- the polyglot context
- Since:
- 0.30
-
isPreInitialization
public boolean isPreInitialization()Returnstrue
if thisContext
is being pre-initialized. For a givenenvironment
, the return value of this method never changes.- Since:
- 19.0
- See Also:
-
getPublicTruffleFile
Returns aTruffleFile
for given path. The returnedTruffleFile
access depends on the file system used by the context and can vary from all access in case ofallowed IO
to no access in case ofdenied IO
. When IO is not enabled by theContext
theTruffleFile
operations throwSecurityException
. ThegetPublicTruffleFile
method should be used to access user files or to implement language IO builtins.- Parameters:
path
- the absolute or relative path to createTruffleFile
for- Returns:
TruffleFile
- Throws:
UnsupportedOperationException
- when theFileSystem
supports onlyURI
IllegalArgumentException
- if thepath
string cannot be converted to aPath
- Since:
- 19.3.0
- See Also:
-
getPublicTruffleFile
Returns aTruffleFile
for given path. SeegetPublicTruffleFile(String)
for detailed information.- Parameters:
uri
- theURI
to createTruffleFile
for- Returns:
TruffleFile
- Throws:
UnsupportedOperationException
- whenURI
scheme is not supportedIllegalArgumentException
- if preconditions on theuri
do not hold.FileSystemNotFoundException
- is the file system, identified by theuri
, does not exist and cannot be created automatically- Since:
- 19.3.0
-
getInternalTruffleFile
Returns aTruffleFile
for given path. This method allows to access files in the guest language home even if file system privileges might be limited or denied. If the path locates a file under the guest language home it is guaranteed that the returnedTruffleFile
has at least read access. Otherwise, the returnedTruffleFile
access depends on the file system used by the context and can vary from all access in case of allowed IO to no access in case of denied IO. ThegetInternalTruffleFile
method should be used to read language standard libraries in a language home. This method is an equivalent togetTruffleFileInternal(path, p -> true)
. For security reasons the language should check that the file is a language source file in language standard libraries folder before using this method for a file in a language home. For performance reasons consider to usegetTruffleFileInternal(String, Predicate)
and perform the language standard libraries check using a predicate.- Parameters:
path
- the absolute or relative path to createTruffleFile
for- Returns:
TruffleFile
- Throws:
UnsupportedOperationException
- when theFileSystem
supports onlyURI
IllegalArgumentException
- if thepath
string cannot be converted to aPath
- Since:
- 19.3.0
- See Also:
-
getInternalTruffleFile
- Parameters:
uri
- theURI
to createTruffleFile
for- Returns:
TruffleFile
- Throws:
UnsupportedOperationException
- whenURI
scheme is not supportedIllegalArgumentException
- if preconditions on theuri
do not hold.FileSystemNotFoundException
- is the file system, identified by theuri
, does not exist and cannot be created automatically- Since:
- 19.3.0
- See Also:
-
getTruffleFileInternal
Returns aTruffleFile
for the given path. This method allows to access files in the guest language home even if file system privileges might be limited or denied. If the path locates a file under the guest language home and satisfies the givenfilter
, it is guaranteed that the returnedTruffleFile
has at least read access. Otherwise, the returnedTruffleFile
access depends on the file system used by the context and can vary from all access in case of allowed IO to no access in case of denied IO.A common use case for this method is a filter granting read access to the language standard libraries.
The method performs the following checks:
- If the IO is enabled by the
Context
an accessibleTruffleFile
is returned without any other checks. - If the given path does not locate a file in a language home a
TruffleFile
with no access is returned. - If the given filter accepts the file a readable
TruffleFile
is returned. Otherwise, aTruffleFile
with no access is returned.
The relation to
getPublicTruffleFile(String)
andgetInternalTruffleFile(String)
is:- The
getPublicTruffleFile(String)
is equivalent togetTruffleFileInternal(path, p -> false)
. - The
getInternalTruffleFile(String)
is equivalent togetTruffleFileInternal(path, p -> true)
.
- Parameters:
path
- the absolute or relative path to createTruffleFile
forfilter
- to enable read access toTruffleFile
. Multiple invocations offilter.test(file)
must consistently returntrue
or consistently returnfalse
for a given path.- Returns:
TruffleFile
- Throws:
UnsupportedOperationException
- when theFileSystem
supports onlyURI
IllegalArgumentException
- if thepath
string cannot be converted to aPath
- Since:
- 21.1.0
- See Also:
- If the IO is enabled by the
-
getTruffleFileInternal
Returns aTruffleFile
for given URI. SeegetTruffleFileInternal(String, Predicate)
for detailed information.- Parameters:
uri
- theURI
to createTruffleFile
forfilter
- to enable read access toTruffleFile
. Multiple invocations offilter.test(file)
must consistently returntrue
or consistently returnfalse
for a given path.- Returns:
TruffleFile
- Throws:
UnsupportedOperationException
- when theFileSystem
supports onlyURI
IllegalArgumentException
- if preconditions on theuri
do not hold.FileSystemNotFoundException
- is the file system, identified by theuri
, does not exist and cannot be created automatically- Since:
- 21.1.0
- See Also:
-
getCurrentWorkingDirectory
Gets the current working directory. The current working directory is used to resolve non absolute paths inTruffleFile
methods.- Returns:
- the current working directory
- Throws:
SecurityException
- if thefilesystem
denies reading of the current working directory- Since:
- 19.0
-
setCurrentWorkingDirectory
Sets the current working directory. The current working directory is used to resolve non absolute paths inTruffleFile
methods.- Parameters:
currentWorkingDirectory
- the new current working directory- Throws:
UnsupportedOperationException
- if setting of the current working directory is not supportedIllegalArgumentException
- if thecurrentWorkingDirectory
is not a valid current working directorySecurityException
- ifcurrentWorkingDirectory
is not readable- Since:
- 19.0
-
getFileNameSeparator
Returns the name separator used to separate names inTruffleFile
's path string.- Returns:
- the name separator
- Since:
- 19.0
-
getPathSeparator
Returns the path separator used to separate filenames in a path list. On UNIX the path separator is':'
. On Windows it's';'
.- Returns:
- the path separator
- Since:
- 19.1.0
-
registerService
Registers additional services provided by the language. The registered services are made available to users vialookup(com.oracle.truffle.api.nodes.LanguageInfo, java.lang.Class)
query method.For each service interface enumerated in
language registration
the language has to register a single service implementation.This method can be called only during the execution of the
createContext method
, then the services are collected and cannot be changed anymore.- Parameters:
service
- a service to be returned from associatedlookup method
- Throws:
IllegalStateException
- if the method is called outside ofTruffleLanguage.createContext(com.oracle.truffle.api.TruffleLanguage.Env)
method- Since:
- 19.0
-
isCreateProcessAllowed
public boolean isCreateProcessAllowed()Returnstrue
if the creation of a sub-process is allowed in the current environment.- Since:
- 19.1.0
- See Also:
-
newProcessBuilder
Creates a new process builder with the specified operating program and arguments.- Parameters:
command
- the executable and its arguments- Throws:
SecurityException
- when process creation is not allowed- Since:
- 19.1.0
-
getEnvironment
Returns an unmodifiable map of the process environment. When theContext
is configured withEnvironmentAccess.INHERIT
it returns theSystem.getenv()
and the environment variables configured on theContext
. For theEnvironmentAccess.NONE
only the environment variables configured on theContext
are returned.- Returns:
- the process environment as a map of variable names to values
- Since:
- 19.1.0
-
createTempFile
public TruffleFile createTempFile(TruffleFile dir, String prefix, String suffix, FileAttribute<?>... attrs) throws IOException Creates a new empty file in the specified or default temporary directory, using the given prefix and suffix to generate its name.This method provides only part of a temporary file facility. To arrange for a file created by this method to be deleted automatically the resulting file must be opened using the
DELETE_ON_CLOSE
option. In this case the file is deleted when the appropriateclose
method is invoked. Alternatively, ashutdown hook
may be used to delete the file automatically.- Parameters:
dir
- the directory in which the file should be created ornull
for a default temporary directoryprefix
- the prefix to generate the file's name ornull
suffix
- the suffix to generate the file's name ornull
in which case ".tmp
" is usedattrs
- the optional attributes to set atomically when creating the file- Returns:
- the
TruffleFile
representing the newly created file that did not exist before this method was invoked - Throws:
IOException
- in case of IO errorIllegalArgumentException
- if the prefix or suffix cannot be used to generate a valid file nameUnsupportedOperationException
- if the attributes contain an attribute which cannot be set atomically orFileSystem
does not support default temporary directorySecurityException
- if theFileSystem
denied the operation- Since:
- 19.3.0
-
createTempDirectory
public TruffleFile createTempDirectory(TruffleFile dir, String prefix, FileAttribute<?>... attrs) throws IOException Creates a new directory in the specified or default temporary directory, using the given prefix to generate its name.This method provides only part of a temporary file facility. A
shutdown hook
may be used to delete the directory automatically.- Parameters:
dir
- the directory in which the directory should be created ornull
for a default temporary directoryprefix
- the prefix to generate the directory's name ornull
attrs
- the optional attributes to set atomically when creating the directory- Returns:
- the
TruffleFile
representing the newly created directory that did not exist before this method was invoked - Throws:
IOException
- in case of IO errorIllegalArgumentException
- if the prefix cannot be used to generate a valid file nameUnsupportedOperationException
- if the attributes contain an attribute which cannot be set atomically orFileSystem
does not support default temporary directorySecurityException
- if theFileSystem
denied the operation- Since:
- 19.3.0
-
createHostAdapterClass
Deprecated.since 22.1; replaced bycreateHostAdapter(Object[])
.- Since:
- 20.3.0
-
createHostAdapterClassWithStaticOverrides
@Deprecated(since="22.1") public Object createHostAdapterClassWithStaticOverrides(Class<?>[] types, Object classOverrides) Deprecated.since 22.1; replaced bycreateHostAdapterWithClassOverrides(Object[], Object)
.- Since:
- 20.3.0
-
createHostAdapter
Creates a Java host adapter class that can be instantiated with a guest object (as the last argument) in order to create adapter instances of the provided host types, (non-final) methods of which delegate to the guest object's invocable members. Implementations must be allowed for these types. The returned host adapter class is an instantiable host object that is also a meta object, soisMetaInstance
can be used to check if an object is an instance of this adapter class. See usage example below.Please note that only classes from the unnamed module or classes exported to the unnamed module can be used in
types
. The generated host adapter class is also in the unnamed module.A host class is generated as follows:
For every protected or public constructor in the extended class, the adapter class will have one public constructor (visibility of protected constructors in the extended class is promoted to public).
For every super constructor, a constructor taking a trailing
Value
argument preceded by original constructor's arguments is generated. When such a constructor is invoked, the passedValue
's member functions are used to implement and/or override methods on the original class, dispatched by name. A single invocable member will act as the implementation for all overloaded methods of the same name. When methods on an adapter instance are invoked, the functions are invoked having theValue
passed in the instance constructor as their receiver. Subsequent changes to the members of thatValue
(reassignment or removal of its functions) are reflected in the adapter instance; the method implementations are not bound to functions at constructor invocation time.The generated host class extends all non-final public or protected methods, and forwards their invocations to the guest object provided to the constructor. If the guest object does not contain an invocable member with that name, the super/default method is invoked instead. If the super method is abstract, an
AbstractMethodError
is thrown.If the original types collectively have only one abstract method, or have several of them, but all share the same name, the constructor(s) will check if the
Value
is executable, and if so, will use the passed function as the implementation for all abstract methods. For consistency, any concrete methods sharing the single abstract method name will also be overridden by the function.For non-void methods, all the conversions supported by
Value.as(java.lang.Class<T>)
will be in effect to coerce the guest methods' return value to the expected Java return type.Instances of the host class have the following additional special members:
super
: provides access to the super methods of the host class via a wrapper object. Can be used to call super methods from guest method overrides.this
: returns the original guest object.
Example:
Object hostClass = env.createHostAdapter(new Object[]{ env.asHostSymbol(Superclass.class), env.asHostSymbol(Interface.class)}); // generates a class along the lines of: public class Adapter extends Superclass implements Interface { private Value delegate; public Adapter(Value delegate) { this.delegate = delegate; } public method(Object... args) { if (delegate.canInvokeMember("method") { return delegate.invokeMember("method", args); } else { return super.method(args); } } } // and can be instantiated as follows: Object instance = InteropLibrary.getUncached().instantiate(hostClass, guestObject); assert InteropLibrary.getUncached().isMetaInstance(hostClass, instance);
- Parameters:
types
- the types to extend. Must be non-null and contain at least one extensible superclass or interface, and at most one superclass. All types must be public, accessible, and allow implementation.- Returns:
- a host class that can be instantiated to create instances of a host class that extends all the provided host types. The host class may be cached.
- Throws:
IllegalArgumentException
- if the types are not extensible or more than one superclass is given.SecurityException
- if host access does not allow creating adapter classes for these types.UnsupportedOperationException
- if creating adapter classes is not supported on this runtime at all, which is currently the case for native images.NullPointerException
- iftypes
is null- Since:
- 22.1
- See Also:
-
createHostAdapterWithClassOverrides
LikecreateHostAdapter(Object[])
but creates a Java host adapter class with class-level overrides, i.e., the guest object provided asclassOverrides
is statically bound to the class rather than instances of the class. Returns a host class that can be instantiated to create instances of the provided hosttypes
, (non-final) methods of which delegate to the guest object provided asclassOverrides
.Allows creating host adapter class hierarchies, i.e., the returned class can be used as a superclass of other host adapter classes. Note that classes created with method cannot be cached. Therefore, this feature should be used sparingly.
See
createHostAdapter(Object[])
for more details.- Parameters:
types
- the types to extend. Must be non-null and contain at least one extensible superclass or interface, and at most one superclass. All types must be public, accessible, and allow implementation.classOverrides
- a guest object with class-level overrides. If not null, the object is bound to the class, not to any instance. Consequently, the generated constructors are changed to not take an object; all instances will share the same overrides object. Note that since a new class has to be generated for every overrides object instance and cannot be shared, use of this feature is discouraged; it is provided only for compatibility reasons.- Returns:
- a host class symbol that can be instantiated to create instances of a host class that extends all the provided host types.
- Throws:
IllegalArgumentException
- if the types are not extensible or more than one superclass is given.SecurityException
- if host access does not allow creating adapter classes for these types.UnsupportedOperationException
- if creating adapter classes is not supported on this runtime at all, which is currently the case for native images.NullPointerException
- if eithertypes
orclassOverrides
is null.- Since:
- 22.1
- See Also:
-
getInternalResource
public TruffleFile getInternalResource(Class<? extends InternalResource> resource) throws IOException Returns theTruffleFile
representing the target directory of an internal resource. The internal resource is guaranteed to be fullyInternalResource.unpackFiles(InternalResource.Env, Path)
s unpacked} before this method returns. When this method is called for the first time and the resource is not cached than the resource will be unpacked. Unpacking an internal resource can be an expensive operation, but the implementation makes sure that unpacked internal resources are cached.The returned
TruffleFile
will only grant read-only access to the target directory, but access is provided even if IO access is disabled.On a HotSpot VM the internal resource is typically cached in the user directory, so unpacking would be repeated once per operating system user. When the language was compiled using native-image internal resources are unpacked at native-image compile time and stored relative to the native-image.
- Parameters:
resource
- the resource class to load- Throws:
IllegalArgumentException
- ifresource
is not associated with this languageIOException
- in case of IO error- Since:
- 23.1
-
getInternalResource
Returns theTruffleFile
representing the target directory of an internal resource. Unlike thegetInternalResource(Class)
, this method can be used for optional resources whose classes may not exist at runtime. In this case the optional resource must be unpacked at build time, seeEngine.copyResources(Path, String...)
. If the resource with the specifiedresourceId
is not associated to this language, the function returnsnull
.- Parameters:
resourceId
- unique id of the resource to be loaded- Returns:
- internal resource directory or
null
if resource with theresourceId
is not associated with this language - Throws:
IOException
- in case of IO error- Since:
- 23.1
- See Also:
-
getLogger
Find or create a context-bound logger. The returnedTruffleLogger
always uses a logging handler and options from this execution environment context and does not depend on being entered on any thread.If a logger with a given name already exists it's returned. Otherwise, a new logger is created.
Unlike loggers created by
TruffleLogger.getLogger
loggers created by this method are bound to a single context. There may be more logger instances having the same name but each bound to a different context. Languages should never store the returned logger into a static field. If the context policy is more permissive thanTruffleLanguage.ContextPolicy.EXCLUSIVE
the returned logger must not be stored in a TruffleLanguage subclass. It is recommended to create all language loggers inTruffleLanguage.createContext(Env)
.- Parameters:
loggerName
- the name of aTruffleLogger
, if aloggerName
is null or empty a root logger for language or instrument is returned- Returns:
- a
TruffleLogger
- Since:
- 21.1
-
getLogger
Find or create a context-bound logger. The returnedTruffleLogger
always uses a logging handler and options from this execution environment context and does not depend on being entered on any thread.If a logger with a given name already exists it's returned. Otherwise, a new logger is created.
Unlike loggers created by
TruffleLogger.getLogger
loggers created by this method are bound to a single context. There may be more logger instances having the same name but each bound to a different context. Languages should never store the returned logger into a static field. If the context policy is more permissive thanTruffleLanguage.ContextPolicy.EXCLUSIVE
the returned logger must not be stored in a TruffleLanguage subclass. It is recommended to create all language loggers inTruffleLanguage.createContext(Env)
.- Parameters:
forClass
- theClass
to create a logger for- Returns:
- a
TruffleLogger
- Since:
- 21.1
-
submitThreadLocal
Submits a thread local action to be performed at the next guest language safepoint on a provided set of threads, once for each thread. If the threads array isnull
then the thread local action will be performed on all alive threads. The submitted actions are processed in the same order as they are submitted in. The action can be synchronous or asynchronous, side-effecting or non-side-effecting. Please seeThreadLocalAction
for details.It is ensured that a thread local action will get processed as long as the thread stays active for this context. If a thread becomes inactive before the action can get processed then the action will not be performed for this thread. If a thread becomes active while the action is being processed then the action will be performed for that thread as long as the thread filter includes the thread or
null
was passed. Already started synchronous actions will block on activation of a new thread. If the synchronous action was not yet started on any thread, then the synchronous action will also be performed for the newly activated thread.The method returns a
Future
instance that allows to wait for the thread local action to complete or to cancel a currently performed event.Example Usage:
Env env; // supplied env.submitThreadLocal(null, new ThreadLocalAction(true, true) { @Override protected void perform(Access access) { // perform action } });
By default thread-local actions are executed once per configured thread and do not repeat themselves. If a ThreadLocalAction is configured to be
recurring
then the action will automatically be rescheduled in the same configuration until it iscancelled
. For recurring actions, an invocation ofFuture.get()
will only wait for the first action to to be performed.Future.isDone()
will returntrue
only if the action was canceled. Canceling a recurring action will result in the current event being canceled and no further events being submitted. Using recurring events should be preferred over submitting the event again for the current thread while performing the thread-local action as recurring events are also resubmitted in case all threads leave and later reenter.If the thread local action future needs to be waited on and this might be prone to deadlocks the
blocking API
can be used to allow other thread local actions to be processed while the current thread is waiting. The returnedFuture.get()
method can be used asTruffleSafepoint.Interruptible
. If the underlying polyglot context is already closed, the method returns a completedFuture
.- Parameters:
threads
- the threads to execute the action on.null
for all threadsaction
- the action to perform on that thread.- Since:
- 21.1
- See Also:
-
registerOnDispose
RegistersCloseable
for automatic close on context dispose. In most cases, closeable should be closed using try-with-resources construct. When a closeable must keep being opened for the lifetime of a context it should be registered using this method for automatic close on context dispose. The registeredCloseable
is weakly referenced. The guest language must strongly reference it otherwise, it may be garbage collected before it's closed.If the registered closeable throws an
IOException
during close, the thrown exception does not prevent successful context dispose. The IOException is logged to the engine logger with aLevel.WARNING
level. Other exceptions are rethrown as internalPolyglotException
.- Parameters:
closeable
- to be closed on context dispose.- Since:
- 21.2
-
getSandboxPolicy
Returns the context'sSandboxPolicy
. A language can use the returned sandbox policy to make language-specific verifications that the sandbox requirements are met. These verifications should be made as early as possible in theTruffleLanguage.createContext(Env)
method.- Since:
- 23.0
- See Also:
-
getScopePublic
Returns the scope object of a non-nullpublic language
. The returned value follows the contract ofTruffleLanguage.getScope(Object)
of the other language, therefore it must be aninterop scope object
and may haveparent scopes
. The bindings object exposes all top scopes variables as flattenedmembers
. In addition to being a scope the returned object may implement any number of theinterop traits
. The interop members of the returned object are typically writable, but that is not guaranteed.The suffix
public
in the method name indicates that the result of this method is safe to be exposed by default to guest applications. For example, languages should use this method to implement the semantics of their polyglot bindings builtin, but is not limited to that.All
public
languages witheval permissions
are accessible. If a language is not accessible then anSecurityException
is thrown. The scope of the current language is always accessible, but it is recommended to use a language specific way to access symbols of the current language.Languages should check for
eval permissions
for eachpublic language
prior to calling this method, otherwise it might causeSecurityException
if not sufficient privileges are available.- Returns:
- the scope, or
null
if the requested language does not support such a concept - Throws:
IllegalStateException
- if polyglot context associated with this environment is not enteredSecurityException
- if polyglot scope access is not enabled for this language.IllegalArgumentException
- Since:
- 24.1
- See Also:
-
getScopeInternal
Returns the scope object of a non-nullinternal language
. Works the same asgetScopePublic(LanguageInfo)
but it also returns scopes of internal and dependent languages.The suffix
internal
in the method name indicates that the result of this method is not safe to be exposed to arbitrary guest code, by default. UsegetScopePublic(LanguageInfo)
for that purpose instead. For example, this method could be used to access a fixed set of symbols from the Truffle Native Interface, e.g. to load native language extensions. Languages may decide to expose scopes of internal languages to arbitrary guest code for testing purposes. Make sure this option is disabled by default and enabled using aninternal
option only.The scope of the current language is always accessible, but it is recommended to use a language specific way to access symbols of the current language.
It is recommended to only use this method for
internal
ordependent languages
. For convenience, this method will also succeed for all accessiblepublic languages
witheval permissions
.- Returns:
- the scope, or
null
if the requested language does not support such a concept - Throws:
IllegalStateException
- if polyglot context associated with this environment is not enteredSecurityException
- if polyglot scope access is not enabled for this language.- Since:
- 24.1
- See Also:
-
createHostAdapter(Object[])
.