public static final class TruffleLanguage.Env extends Object
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.Modifier and Type | Method and Description |
---|---|
void |
addToHostClassPath(TruffleFile entry)
Adds an entry to the Java host class loader.
|
Object |
asBoxedGuestValue(Object guestObject)
Wraps primitive interop values in a TruffleObject exposing their methods as members.
|
Object |
asGuestValue(Object hostObject)
Converts a existing Java host object to a guest language value.
|
Throwable |
asHostException(Throwable exception)
Unwraps a host exception thrown by a Java method invocation.
|
Object |
asHostObject(Object value)
Returns the java host representation of a Truffle guest object if it represents a Java
host language object.
|
Object |
asHostSymbol(Class<?> symbolClass)
Converts a Java class to a host symbol as if by
lookupHostSymbol(symbolClass.getName()) but without an actual lookup. |
Object |
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.
|
Object |
createHostAdapterWithClassOverrides(Object[] types,
Object classOverrides)
Like
TruffleLanguage.Env.createHostAdapter(Object[]) but creates a Java host adapter class with
class-level overrides, i.e., the guest object provided as classOverrides is
statically bound to the class rather than instances of the class. |
Thread |
createSystemThread(Runnable runnable)
Creates a new thread designed to process language internal tasks in the background.
|
Thread |
createSystemThread(Runnable runnable,
ThreadGroup threadGroup)
Creates a new thread designed to process language internal tasks in the background.
|
TruffleFile |
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.
|
TruffleFile |
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.
|
OutputStream |
err()
Standard error writer provided by
Context.Builder.err(OutputStream) this language is being
executed in. |
void |
exportSymbol(String symbolName,
Object value)
Explicitly exports a symbol to the polyglot bindings object.
|
Object |
findMetaObject(Object value)
Find a metaobject of a value, if any.
|
String[] |
getApplicationArguments()
Returns the application arguments that were provided for this context.
|
Map<String,Object> |
getConfig()
Configuration arguments passed from an outer language context to an inner language
context.
|
TruffleContext |
getContext()
Returns the polyglot context associated with this environment.
|
TruffleFile |
getCurrentWorkingDirectory()
Gets the current working directory.
|
Map<String,String> |
getEnvironment()
Returns an unmodifiable map of the process environment.
|
String |
getFileNameSeparator()
Returns the name separator used to separate names in
TruffleFile 's path string. |
Map<String,InstrumentInfo> |
getInstruments()
Returns a map instrument-id to instrument instance of all instruments that are installed
in the environment.
|
Map<String,LanguageInfo> |
getInternalLanguages()
Returns all languages that are installed and internally accessible in the environment.
|
TruffleFile |
getInternalTruffleFile(String path)
Returns a
TruffleFile for given path. |
TruffleFile |
getInternalTruffleFile(URI uri)
Returns
TruffleFile for given URI . |
TruffleLogger |
getLogger(Class<?> forClass)
Find or create a context-bound logger.
|
TruffleLogger |
getLogger(String loggerName)
Find or create a context-bound logger.
|
OptionValues |
getOptions()
Returns option values for the options described in
TruffleLanguage.getOptionDescriptors() . |
String |
getPathSeparator()
Returns the path separator used to separate filenames in a path list.
|
Object |
getPolyglotBindings()
Returns a TruffleObject that represents the polyglot bindings.
|
Map<String,LanguageInfo> |
getPublicLanguages()
Returns all languages that are installed and publicly accessible in the environment.
|
TruffleFile |
getPublicTruffleFile(String path)
Returns a
TruffleFile for given path. |
TruffleFile |
getPublicTruffleFile(URI uri)
Returns a
TruffleFile for given path. |
SandboxPolicy |
getSandboxPolicy()
Returns the context's
SandboxPolicy . |
ZoneId |
getTimeZone()
Returns the default time zone of this environment.
|
TruffleFile |
getTruffleFileInternal(String path,
Predicate<TruffleFile> filter)
Returns a
TruffleFile for the given path. |
TruffleFile |
getTruffleFileInternal(URI uri,
Predicate<TruffleFile> filter)
Returns a
TruffleFile for given URI. |
Object |
importSymbol(String symbolName)
Explicitly imports a symbol from the polyglot bindings.
|
InputStream |
in()
Input stream provided by
Context.Builder.in(InputStream)
this language is being executed in. |
boolean |
initializeLanguage(LanguageInfo targetLanguage)
Ensures that the target language is initialized.
|
boolean |
isCreateProcessAllowed()
Returns
true if the creation of a sub-process is allowed in the current
environment. |
boolean |
isCreateThreadAllowed()
Returns
true if the creation of new threads is allowed in the current
environment. |
boolean |
isFileIOAllowed()
Returns
true if access to files is allowed, else false . |
boolean |
isHostException(Throwable exception)
Tests whether an exception is a host exception thrown by a Java Interop method
invocation.
|
boolean |
isHostFunction(Object value)
Returns
true if the argument is a Java host language function wrapped using
Truffle interop. |
boolean |
isHostLookupAllowed()
Returns
true if host access is generally allowed. |
boolean |
isHostObject(Object value)
Returns
true if the argument is Java host language object wrapped using
Truffle interop. |
boolean |
isHostSymbol(Object guestObject)
Returns
true if the argument is a host symbol, representing the constructor and
static members of a Java class, as obtained by e.g. |
boolean |
isInnerContextOptionsAllowed()
Returns
true if context options are allowed to be modified for inner
contexts, or false if not. |
boolean |
isMimeTypeSupported(String mimeType)
Allows it to be determined if this
Context can execute code
written in a language with a given MIME type. |
boolean |
isNativeAccessAllowed()
Returns
true if access to native code is generally allowed. |
boolean |
isPolyglotBindingsAccessAllowed()
Returns
true if polyglot bindings access is allowed, else false
. |
boolean |
isPolyglotEvalAllowed()
Returns
true if polyglot evaluation is allowed, else false . |
boolean |
isPreInitialization()
Returns
true if this Context is being
pre-initialized. |
boolean |
isSocketIOAllowed()
Returns
true if access to network sockets is allowed, else false . |
<T> T |
lookup(Class<T> type)
Looks additional service up.
|
<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.
|
Object |
lookupHostSymbol(String symbolName)
Looks up a Java class in the top-most scope the host environment.
|
TruffleContext.Builder |
newInnerContextBuilder(String... permittedLanguages)
Returns a new context builder useful to create inner context instances.
|
TruffleProcessBuilder |
newProcessBuilder(String... command)
Creates a new process builder with the specified operating program and arguments.
|
TruffleThreadBuilder |
newTruffleThreadBuilder(Runnable runnable)
Creates a builder for threads that have access to the given context.
|
OutputStream |
out()
Standard output writer provided by
Context.Builder.out(OutputStream) this language is being
executed in. |
CallTarget |
parseInternal(Source source,
String... argumentNames)
Parses the source of a public or internal language and returns the parse result as
CallTarget . |
CallTarget |
parsePublic(Source source,
String... argumentNames)
Parses the source of a public language and returns the parse result as
CallTarget
. |
void |
registerOnDispose(Closeable closeable)
Registers
Closeable 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.
|
Future<Void> |
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.
|
public OptionValues getOptions()
TruffleLanguage.getOptionDescriptors()
. The returned options are never
null
.public String[] getApplicationArguments()
null
. It is up to the language
implementation whether and how they are accessible within the guest language scripts.public boolean isCreateThreadAllowed()
true
if the creation of new threads is allowed in the current
environment.TruffleLanguage.Env.newTruffleThreadBuilder(Runnable)
public TruffleThreadBuilder newTruffleThreadBuilder(Runnable runnable)
runnable
- the runnable to run on the threads created by the builder.public Thread createSystemThread(Runnable runnable)
TruffleLanguage.Env.createSystemThread(Runnable, ThreadGroup)
for a detailed description of the
parameters.TruffleLanguage.Env.createSystemThread(Runnable, ThreadGroup)
public Thread createSystemThread(Runnable runnable, ThreadGroup threadGroup)
IllegalStateException
is
thrown. Creating or terminating a system thread does not notify
languages
or instruments'
thread-listeners. Creating a system thread does not cause a transition to multi-threaded
access. The creation 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 an IllegalStateException
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 an
IllegalStateException
is thrown. It's not safe to use the
ExecutorService.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 extendsTruffleLanguage
<SystemThreadLanguage.Context
> { static classContext
{ private finalBlockingQueue
<Runnable
> tasks; private finalTruffleLanguage.Env
env; private volatileThread
systemThread; private volatile boolean cancelled;Context
(TruffleLanguage.Env
env) { this.tasks = newLinkedBlockingQueue
<>(); this.env = env; } } @Override
protectedContext
createContext(TruffleLanguage.Env
env) { return newContext
(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(); } } } }
runnable
- the runnable to run on this thread.threadGroup
- the thread group, passed on to the underlying Thread
.IllegalStateException
- if the context is already closed.TruffleLanguage.Env.createSystemThread(Runnable)
public TruffleContext.Builder newInnerContextBuilder(String... permittedLanguages)
By default the inner context inherits none of the access privileges. To inherit access
set TruffleContext.Builder.inheritAllAccess(boolean)
to true
.
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 using TruffleContext.initializePublic(Node, String)
or
evaluate a source using TruffleContext.evalPublic(Node, Source)
.
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 is built
. An
IllegalArgumentException
will be thrown if an unknown or a language
denied by the engine was used.for details on language inner contexts.
public Object getPolyglotBindings()
SecurityException
- if polyglot access is not enabledTruffleLanguage.Env.isPolyglotBindingsAccessAllowed()
public Object importSymbol(String symbolName)
polyglot
bindings
object. Reading a symbol that does not exist will return null
.
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.
symbolName
- the name of the symbol to search fornull
if it does not existSecurityException
- if importing polyglot symbols is not allowedpublic void exportSymbol(String symbolName, Object value)
polyglot
bindings
object. Exporting a symbol with a null
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.
symbolName
- the name with which the symbol should be exported into the polyglot
scopevalue
- the value to export forSecurityException
- if exporting polyglot symbols is not allowedpublic boolean isHostLookupAllowed()
true
if host access is generally allowed. If this method returns
false
then TruffleLanguage.Env.lookupHostSymbol(String)
will always fail. Host lookup
is generally disallowed if the embedder provided a null
host class filter
.public void addToHostClassPath(TruffleFile entry)
TruffleLanguage.Env.lookupHostSymbol(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 be null
.SecurityException
- if the file is not readable
.public Object lookupHostSymbol(String symbolName)
host class filter
prevents access. The returned object is always a
TruffleObject
that represents the class symbol.symbolName
- the qualified class name in the host language.public boolean isHostObject(Object value)
true
if the argument is Java host language object wrapped using
Truffle interop.TruffleLanguage.Env.asHostObject(Object)
public Object asHostObject(Object value)
ClassCastException
if the provided argument is not a
host object
.public Object asGuestValue(Object hostObject)
Context.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
TruffleLanguage.Env.lookupHostSymbol(String)
to lookup the class and then send a NEW interop message
to that object to instantiate it. This method does not respect configured
class filters
.
hostObject
- the host object to convertpublic Object asBoxedGuestValue(Object guestObject)
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 an
IllegalArgumentException
will be thrown.guestObject
- the primitive guest value to boxIllegalArgumentException
- if value is an invalid interop value.TruffleLanguage.Env.asGuestValue(Object)
public boolean isHostFunction(Object value)
true
if the argument is a Java host language function wrapped using
Truffle interop.public Object findMetaObject(Object value)
When no metaobject is known, returns null
. The metaobject is an interop
value. An interop value can be either a TruffleObject
(e.g. a native object
from the other language) to support interoperability between languages or a
String
.
value
- the value to find the meta object for.public boolean isHostException(Throwable exception)
TruffleLanguage.Env.asHostException(Throwable)
.exception
- the Throwable
to testtrue
if the exception
is a host exception, false
otherwiseTruffleLanguage.Env.asHostException(Throwable)
public Throwable asHostException(Throwable exception)
TruffleLanguage.Env.asHostException(Throwable)
.exception
- the host exception to unwrapIllegalArgumentException
- if the exception
is not a host exceptionTruffleLanguage.Env.isHostException(Throwable)
public boolean isHostSymbol(Object guestObject)
true
if the argument is a host symbol, representing the constructor and
static members of a Java class, as obtained by e.g. TruffleLanguage.Env.lookupHostSymbol(java.lang.String)
.TruffleLanguage.Env.lookupHostSymbol(String)
public Object asHostSymbol(Class<?> symbolClass)
lookupHostSymbol(symbolClass.getName())
but without an actual lookup. Must not be
used with Truffle or guest language classes.TruffleLanguage.Env.lookupHostSymbol(String)
public boolean isInnerContextOptionsAllowed()
true
if context options are allowed to be modified for inner
contexts, or false
if not. This method only indicates whether the embedder
granted wildcard all access for new privileges using
Context.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.
TruffleContext.Builder.option(String, String)
public boolean isFileIOAllowed()
true
if access to files is allowed, else false
.public boolean isSocketIOAllowed()
true
if access to network sockets is allowed, else false
.public boolean isNativeAccessAllowed()
true
if access to native code is generally allowed. If this method
returns false
then loading native libraries with the Truffle NFI will fail.public boolean isPolyglotEvalAllowed()
true
if polyglot evaluation is allowed, else false
.
Guest languages should hide or disable all polyglot evaluation builtins if this flag is
set to false
. Note that if polyglot evaluation access is disabled, then the
available languages list
only shows the current language,
dependent languages
and
internal languages
.Context.Builder.allowPolyglotAccess(org.graalvm.polyglot.PolyglotAccess)
public boolean isPolyglotBindingsAccessAllowed()
true
if polyglot bindings access is allowed, else false
. Guest languages should hide or disable all polyglot bindings builtins if this flag is
set to false
. If polyglot bindings access is disabled then
TruffleLanguage.Env.getPolyglotBindings()
, TruffleLanguage.Env.importSymbol(String)
or
TruffleLanguage.Env.exportSymbol(String, Object)
fails with a SecurityException.Context.Builder.allowPolyglotAccess(org.graalvm.polyglot.PolyglotAccess)
public boolean isMimeTypeSupported(String mimeType)
Context
can execute code
written in a language with a given MIME type.Source.getMimeType()
,
TruffleLanguage.Env.parsePublic(Source, String...)
public CallTarget parseInternal(Source source, String... argumentNames)
CallTarget
. The language id
is used to identify the
TruffleLanguage
to use to perform the
TruffleLanguage.parse(com.oracle.truffle.api.TruffleLanguage.ParsingRequest)
. The names of
arguments are parameters for the resulting {#link CallTarget} that allow the
source
to reference the actual parameters passed to
CallTarget.call(java.lang.Object...)
.
Compared to TruffleLanguage.Env.parsePublic(Source, String...)
this method provides also access to
internal
and dependent languages in
addition to public languages. For example, in JavaScript, a call to the eval builtin
should forward to TruffleLanguage.Env.parsePublic(Source, String...)
as it contains code provided by
the guest language user. Parsing regular expressions with the internal regular expression
engine should call TruffleLanguage.Env.parseInternal(Source, String...)
instead, as this is
considered an implementation detail of the language.
It is recommended that the language uses TruffleLanguage.Env.parsePublic(Source, String...)
or
TruffleLanguage.Env.parseInternal(Source, String...)
instead of directly passing the Source to
the parser, in order to support code caching with TruffleLanguage.ContextPolicy.SHARED
and
TruffleLanguage.ContextPolicy.REUSE
.
source
- the source to evaluateargumentNames
- the names of CallTarget.call(java.lang.Object...)
arguments
that can be referenced from the sourceIllegalStateException
- if polyglot context associated with this environment is not
enteredTruffleLanguage.Env.parsePublic(Source, String...)
public CallTarget parsePublic(Source source, String... argumentNames)
CallTarget
. The language id
is used to identify the
TruffleLanguage
to use to perform the
TruffleLanguage.parse(com.oracle.truffle.api.TruffleLanguage.ParsingRequest)
. The names of
arguments are parameters for the resulting {#link CallTarget} that allow the
source
to reference the actual parameters passed to
CallTarget.call(java.lang.Object...)
.
Compared to TruffleLanguage.Env.parseInternal(Source, String...)
this method does only provide
access to non internal, non dependent, public languages. 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 to
TruffleLanguage.Env.parsePublic(Source, String...)
as it contains code provided by the guest
language user. Parsing regular expressions with the internal regular expression engine
should call TruffleLanguage.Env.parseInternal(Source, String...)
instead, as this is considered an
implementation detail of the language.
It is recommended that the language uses TruffleLanguage.Env.parsePublic(Source, String...)
or
TruffleLanguage.Env.parseInternal(Source, String...)
instead of directly passing the Source to
the parser, in order to support code caching with TruffleLanguage.ContextPolicy.SHARED
and
TruffleLanguage.ContextPolicy.REUSE
.
source
- the source to evaluateargumentNames
- the names of CallTarget.call(java.lang.Object...)
arguments
that can be referenced from the sourceIllegalStateException
- if polyglot context associated with this environment is not
enteredTruffleLanguage.Env.parseInternal(Source, String...)
public InputStream in()
Context.Builder.in(InputStream)
this language is being executed in.null
public OutputStream out()
Context.Builder.out(OutputStream)
this language is being
executed in.null
public OutputStream err()
Context.Builder.err(OutputStream)
this language is being
executed in.null
public <T> T lookup(Class<T> type)
language
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 include
Instrumenter
and others.T
- type of requested servicetype
- class of requested servicenull
if there is no such service availablepublic <S> S lookup(InstrumentInfo instrument, Class<S> type)
S
- the requested typeinstrument
- identification of the instrument to querytype
- the class of the requested typenull
if none is foundpublic <S> S lookup(LanguageInfo language, Class<S> type)
TruffleLanguage.Registration.services()
the service lookup will ensure
that the language is loaded and services are registered. The provided langauge and type
must not be null
.S
- the requested typelanguage
- the language to querytype
- the class of the requested typenull
if none is foundregisterService
public boolean initializeLanguage(LanguageInfo targetLanguage)
SecurityException
is
thrown. Then the target language initialization is performed if not already done.targetLanguage
- the language to initializeSecurityException
- if an access to targetLanguage
is not permittedpublic Map<String,LanguageInfo> getInternalLanguages()
looked up
. TruffleLanguage.Env.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.public Map<String,LanguageInfo> getPublicLanguages()
looked up
. TruffleLanguage.Env.parsePublic(Source, String...)
is allowed for all languages returned by this method. This list of languages may be
exposed ot the guest language program.TruffleLanguage.Env.parsePublic(Source, String...)
public Map<String,InstrumentInfo> getInstruments()
looked up
.public ZoneId getTimeZone()
system default
time-zone will
be returned.ZoneId.systemDefault()
public Map<String,Object> getConfig()
TruffleLanguage.Env.newInnerContextBuilder(String...)
.to create inner contexts.
,
to pass configuration objects to the
inner context.
public TruffleContext getContext()
public boolean isPreInitialization()
true
if this Context
is being
pre-initialized. For a given environment
, the return value of this method
never changes.TruffleLanguage.initializeContext(Object)
,
TruffleLanguage.patchContext(Object, Env)
public TruffleFile getPublicTruffleFile(String path)
TruffleFile
for given path. The returned TruffleFile
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
.
When IO is not enabled by the Context
the TruffleFile
operations throw
SecurityException
. The getPublicTruffleFile
method should be used to
access user files or to implement language IO builtins.path
- the absolute or relative path to create TruffleFile
forTruffleFile
UnsupportedOperationException
- when the FileSystem
supports only
URI
IllegalArgumentException
- if the path
string cannot be converted to a
Path
IOAccess
,
Context.Builder.allowIO(IOAccess)
public TruffleFile getPublicTruffleFile(URI uri)
TruffleFile
for given path. See TruffleLanguage.Env.getPublicTruffleFile(String)
for detailed information.uri
- the URI
to create TruffleFile
forTruffleFile
UnsupportedOperationException
- when URI
scheme is not supportedIllegalArgumentException
- if preconditions on the uri
do not hold.public TruffleFile getInternalTruffleFile(String path)
TruffleFile
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 returned
TruffleFile
has at least read access. Otherwise, the returned TruffleFile
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. The getInternalTruffleFile
method should be used to read language standard libraries in a language home. This method
is an equivalent to getTruffleFileInternal(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 use TruffleLanguage.Env.getTruffleFileInternal(String, Predicate)
and perform
the language standard libraries check using a predicate.path
- the absolute or relative path to create TruffleFile
forTruffleFile
UnsupportedOperationException
- when the FileSystem
supports only
URI
IllegalArgumentException
- if the path
string cannot be converted to a
Path
TruffleLanguage.Env.getTruffleFileInternal(String, Predicate)
,
TruffleLanguage.Env.getPublicTruffleFile(java.lang.String)
public TruffleFile getInternalTruffleFile(URI uri)
TruffleFile
for given URI
. See
TruffleLanguage.Env.getInternalTruffleFile(String)
for detailed information.uri
- the URI
to create TruffleFile
forTruffleFile
UnsupportedOperationException
- when URI
scheme is not supportedIllegalArgumentException
- if preconditions on the uri
do not hold.TruffleLanguage.Env.getTruffleFileInternal(URI, Predicate)
,
TruffleLanguage.Env.getPublicTruffleFile(java.net.URI)
public TruffleFile getTruffleFileInternal(String path, Predicate<TruffleFile> filter)
TruffleFile
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 given filter
,
it is guaranteed that the returned TruffleFile
has at least read access.
Otherwise, the returned TruffleFile
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:
Context
an accessible TruffleFile
is
returned without any other checks.TruffleFile
with no access is returned.TruffleFile
is returned.
Otherwise, a TruffleFile
with no access is returned.
The relation to TruffleLanguage.Env.getPublicTruffleFile(String)
and
TruffleLanguage.Env.getInternalTruffleFile(String)
is:
TruffleLanguage.Env.getPublicTruffleFile(String)
is equivalent to
getTruffleFileInternal(path, p -> false)
.TruffleLanguage.Env.getInternalTruffleFile(String)
is equivalent to
getTruffleFileInternal(path, p -> true)
.path
- the absolute or relative path to create TruffleFile
forfilter
- to enable read access to TruffleFile
. Multiple invocations of
filter.test(file)
must consistently return true
or
consistently return false
for a given path.TruffleFile
UnsupportedOperationException
- when the FileSystem
supports only
URI
IllegalArgumentException
- if the path
string cannot be converted to a
Path
TruffleLanguage.Env.getTruffleFileInternal(URI, Predicate)
,
TruffleLanguage.Env.getPublicTruffleFile(String)
,
TruffleLanguage.Env.getInternalTruffleFile(String)
public TruffleFile getTruffleFileInternal(URI uri, Predicate<TruffleFile> filter)
TruffleFile
for given URI. See
TruffleLanguage.Env.getTruffleFileInternal(String, Predicate)
for detailed information.uri
- the URI
to create TruffleFile
forfilter
- to enable read access to TruffleFile
. Multiple invocations of
filter.test(file)
must consistently return true
or
consistently return false
for a given path.TruffleFile
UnsupportedOperationException
- when the FileSystem
supports only
URI
IllegalArgumentException
- if preconditions on the uri
do not hold.TruffleLanguage.Env.getTruffleFileInternal(String, Predicate)
,
TruffleLanguage.Env.getPublicTruffleFile(URI)
,
TruffleLanguage.Env.getInternalTruffleFile(URI)
public TruffleFile getCurrentWorkingDirectory()
TruffleFile
methods.SecurityException
- if the filesystem
denies reading of the
current working directorypublic void setCurrentWorkingDirectory(TruffleFile currentWorkingDirectory)
TruffleFile
methods.currentWorkingDirectory
- the new current working directoryUnsupportedOperationException
- if setting of the current working directory is not
supportedIllegalArgumentException
- if the currentWorkingDirectory
is not a valid
current working directorySecurityException
- if currentWorkingDirectory
is not readablepublic String getFileNameSeparator()
TruffleFile
's path string.public String getPathSeparator()
':'
. On Windows it's ';'
.public void registerService(Object service)
TruffleLanguage.Env.lookup(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.
service
- a service to be returned from associated
lookup method
IllegalStateException
- if the method is called outside of
TruffleLanguage.createContext(com.oracle.truffle.api.TruffleLanguage.Env)
methodpublic boolean isCreateProcessAllowed()
true
if the creation of a sub-process is allowed in the current
environment.TruffleLanguage.Env.newProcessBuilder(java.lang.String...)
public TruffleProcessBuilder newProcessBuilder(String... command)
command
- the executable and its argumentsSecurityException
- when process creation is not allowedpublic Map<String,String> getEnvironment()
Context
is
configured with EnvironmentAccess.INHERIT
it returns the System.getenv()
and the environment variables configured on the Context
. For the
EnvironmentAccess.NONE
only the environment variables configured on the
Context
are returned.public TruffleFile createTempFile(TruffleFile dir, String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
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 appropriate close
method is invoked. Alternatively,
a shutdown hook
may be used to delete the file
automatically.
dir
- the directory in which the file should be created or null
for a
default temporary directoryprefix
- the prefix to generate the file's name or null
suffix
- the suffix to generate the file's name or null
in which case
".tmp
" is usedattrs
- the optional attributes to set atomically when creating the fileTruffleFile
representing the newly created file that did not exist
before this method was invokedIOException
- 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 or FileSystem
does not support default temporary
directorySecurityException
- if the FileSystem
denied the operationpublic TruffleFile createTempDirectory(TruffleFile dir, String prefix, FileAttribute<?>... attrs) throws IOException
This method provides only part of a temporary file facility. A
shutdown hook
may be used to delete the directory
automatically.
dir
- the directory in which the directory should be created or null
for a
default temporary directoryprefix
- the prefix to generate the directory's name or null
attrs
- the optional attributes to set atomically when creating the directoryTruffleFile
representing the newly created directory that did not
exist before this method was invokedIOException
- 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 or FileSystem
does not support default temporary
directorySecurityException
- if the FileSystem
denied the operationpublic Object createHostAdapter(Object[] types)
isMetaInstance
can
be used to check if an object is an instance of this adapter class. See usage example
below.
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 passed Value
'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 the Value
passed in the instance constructor as their receiver. Subsequent changes to the members
of that Value
(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);
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.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 types
is nullTruffleLanguage.Env.createHostAdapterWithClassOverrides(Object[], Object)
public Object createHostAdapterWithClassOverrides(Object[] types, Object classOverrides)
TruffleLanguage.Env.createHostAdapter(Object[])
but creates a Java host adapter class with
class-level overrides, i.e., the guest object provided as classOverrides
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 host types
, (non-final) methods
of which delegate to the guest object provided as classOverrides
.
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 TruffleLanguage.Env.createHostAdapter(Object[])
for more details.
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.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 either types
or classOverrides
is null.TruffleLanguage.Env.createHostAdapter(Object[])
public TruffleLogger getLogger(String loggerName)
TruffleLogger
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 than TruffleLanguage.ContextPolicy.EXCLUSIVE
the returned
logger must not be stored in a TruffleLanguage subclass. It is recommended to create all
language loggers in TruffleLanguage.createContext(Env)
.
loggerName
- the name of a TruffleLogger
, if a loggerName
is null or
empty a root logger for language or instrument is returnedTruffleLogger
public TruffleLogger getLogger(Class<?> forClass)
TruffleLogger
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 than TruffleLanguage.ContextPolicy.EXCLUSIVE
the returned
logger must not be stored in a TruffleLanguage subclass. It is recommended to create all
language loggers in TruffleLanguage.createContext(Env)
.
forClass
- the Class
to create a logger forTruffleLogger
public Future<Void> submitThreadLocal(Thread[] threads, ThreadLocalAction action)
null
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 see
ThreadLocalAction
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 is
cancelled
. For recurring actions, an invocation of
Future.get()
will only wait for the first action to to be performed.
Future.isDone()
will return true
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 returned Future.get()
method can be used as
TruffleSafepoint.Interruptible
. If the underlying polyglot context is already closed, the method
returns a completed Future
.
threads
- the threads to execute the action on. null
for all threadsaction
- the action to perform on that thread.ThreadLocalAction
,
TruffleSafepoint
public void registerOnDispose(Closeable closeable)
Closeable
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 registered Closeable
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 a Level.WARNING
level. Other exceptions are rethrown as
internal PolyglotException
.
closeable
- to be closed on context dispose.public SandboxPolicy getSandboxPolicy()
SandboxPolicy
. 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 the
TruffleLanguage.createContext(Env)
method.SandboxPolicy
,
TruffleLanguage.createContext(Env)