Class TruffleLanguage.Env

java.lang.Object
com.oracle.truffle.api.TruffleLanguage.Env
Enclosing class:
TruffleLanguage<C>

public static final class TruffleLanguage.Env extends Object
Represents execution environment of the 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 Details

    • getOptions

      public OptionValues getOptions()
      Returns option values for the options described in TruffleLanguage.getOptionDescriptors(). The returned options are never null.
      Since:
      0.27
    • getApplicationArguments

      public String[] getApplicationArguments()
      Returns the application arguments that were provided for this context. The arguments array and its elements are never null. 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()
      Returns true if the creation of new threads is allowed in the current environment.
      Since:
      0.28
      See Also:
    • createThread

      @Deprecated public Thread createThread(Runnable runnable)
      Deprecated.
      Creates a new thread that has access to the current language context. See createThread(Runnable, TruffleContext, ThreadGroup, long) for a detailed description of the parameters. The group is null and stackSize set to 0.
      Since:
      0.28
    • createThread

      @Deprecated public Thread createThread(Runnable runnable, TruffleContext context)
      Deprecated.
      Creates a new thread that has access to the given context. See createThread(Runnable, TruffleContext, ThreadGroup, long) for a detailed description of the parameters. The group is null and stackSize set to 0.
      Since:
      0.28
      See Also:
    • createThread

      @Deprecated public Thread createThread(Runnable runnable, TruffleContext context, ThreadGroup group)
      Deprecated.
      Creates a new thread that has access to the given context. See createThread(Runnable, TruffleContext, ThreadGroup, long) for a detailed description of the parameters. The stackSize set to 0.
      Since:
      0.28
      See Also:
    • createThread

      @Deprecated public Thread createThread(Runnable runnable, TruffleContext context, ThreadGroup group, long stackSize)
      Deprecated.
      Creates a new thread that has access to the given context. A thread is initialized when it is started and disposed 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 an AssertionError is thrown. It's not safe to use the ExecutorService.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 by newInnerContextBuilder(String...).build(), or the context associated with this environment obtained from getContext().

      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 underlying Thread.
      stackSize - the desired stack size for the new thread, or zero if this parameter is to be ignored.
      Throws:
      IllegalStateException - if thread creation is not allowed.
      Since:
      0.28
      See Also:
    • newTruffleThreadBuilder

      public TruffleThreadBuilder newTruffleThreadBuilder(Runnable runnable)
      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

      public Thread createSystemThread(Runnable runnable)
      Creates a new thread designed to process language internal tasks in the background. See createSystemThread(Runnable, ThreadGroup) for a detailed description of the parameters.
      Since:
      22.3
      See Also:
    • createSystemThread

      public Thread createSystemThread(Runnable runnable, ThreadGroup threadGroup)
      Creates a new thread designed to process language internal tasks in the background. The created thread cannot enter the context, if it tries an 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 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 underlying Thread.
      Throws:
      IllegalStateException - if the context is already closed.
      Since:
      22.3
      See Also:
    • newContextBuilder

      @Deprecated public TruffleContext.Builder newContextBuilder()
      Deprecated.
      use newInnerContextBuilder(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

      public TruffleContext.Builder newInnerContextBuilder(String... permittedLanguages)
      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) 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).

      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 is built. An IllegalArgumentException will be thrown if an unknown or a language denied by the engine was used.
      Since:
      22.3
      See Also:
    • getPolyglotBindings

      public Object 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

      public Object importSymbol(String symbolName)
      Explicitly imports a symbol from the polyglot bindings. The behavior of this method is equivalent to sending a READ message to the 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.

      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

      public void exportSymbol(String symbolName, Object value)
      Explicitly exports a symbol to the polyglot bindings object. The behavior of this method is equivalent to sending a WRITE message to the 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.

      Parameters:
      symbolName - the name with which the symbol should be exported into the polyglot scope
      value - the value to export for
      Throws:
      SecurityException - if exporting polyglot symbols is not allowed
      Since:
      0.27
    • isHostLookupAllowed

      public boolean isHostLookupAllowed()
      Returns true if host access is generally allowed. If this method returns false then lookupHostSymbol(String) will always fail. Host lookup is generally disallowed if the embedder provided a null host class filter.
      Since:
      0.27
    • addToHostClassPath

      public void addToHostClassPath(TruffleFile entry)
      Adds an entry to the Java host class loader. All classes looked up with 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.

      Note that classes added by this method are in the unnamed module.

      Throws:
      SecurityException - if the file is not readable.
      Since:
      19.0
    • lookupHostSymbol

      public Object lookupHostSymbol(String symbolName)
      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 a host class filter prevents access. The returned object is always a TruffleObject that represents the class symbol.
      Parameters:
      symbolName - the qualified class name in the host language.
      Since:
      0.27
    • isHostObject

      public boolean isHostObject(Object value)
      Returns true if the argument is Java host language object wrapped using Truffle interop.
      Since:
      19.0
      See Also:
    • asHostObject

      public Object asHostObject(Object value)
      Returns the java host representation of a Truffle guest object if it represents a Java host language object. Throws ClassCastException if the provided argument is not a host object.
      Since:
      19.0
    • asGuestValue

      public Object asGuestValue(Object hostObject)
      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 in 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 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.

      Parameters:
      hostObject - the host object to convert
      Since:
      19.0
    • asBoxedGuestValue

      public Object asBoxedGuestValue(Object guestObject)
      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 an IllegalArgumentException 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

      public boolean isHostFunction(Object value)
      Returns true if the argument is a Java host language function wrapped using Truffle interop.
      Since:
      19.0
    • findMetaObject

      public Object findMetaObject(Object value)
      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 a TruffleObject (e.g. a native object from the other language) to support interoperability between languages or a String.

      Parameters:
      value - the value to find the meta object for.
      Since:
      19.0
    • isHostException

      public boolean isHostException(Throwable exception)
      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 using asHostException(Throwable).
      Parameters:
      exception - the Throwable to test
      Returns:
      true if the exception is a host exception, false otherwise
      Since:
      19.0
      See Also:
    • asHostException

      public Throwable asHostException(Throwable exception)
      Unwraps a host exception thrown by a Java method invocation. Host exceptions may be thrown by interoperability messages. The host exception may be unwrapped using asHostException(Throwable).
      Parameters:
      exception - the host exception to unwrap
      Returns:
      the original Java exception
      Throws:
      IllegalArgumentException - if the exception is not a host exception
      Since:
      19.0
      See Also:
    • isHostSymbol

      public 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. lookupHostSymbol(java.lang.String).
      Since:
      19.0
      See Also:
    • asHostSymbol

      public Object asHostSymbol(Class<?> symbolClass)
      Converts a Java class to a host symbol as if by lookupHostSymbol(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()
      Returns 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.

      Since:
      22.3
      See Also:
    • isIOAllowed

      @Deprecated(since="23.0") public boolean isIOAllowed()
      Deprecated.
      since 23.0; replaced by isFileIOAllowed().
      Returns true if access to files is allowed, else false.
      Since:
      22.3
    • isFileIOAllowed

      public boolean isFileIOAllowed()
      Returns true if access to files is allowed, else false.
      Since:
      23.0
    • isSocketIOAllowed

      public boolean isSocketIOAllowed()
      Returns true if access to network sockets is allowed, else false.
      Since:
      23.0
    • isNativeAccessAllowed

      public boolean isNativeAccessAllowed()
      Returns true if access to native code is generally allowed. If this method returns false then loading native libraries with the Truffle NFI will fail.
      Since:
      19.0
    • isPolyglotEvalAllowed

      @Deprecated public boolean isPolyglotEvalAllowed()
      Deprecated.
      in 24.1 use isPolyglotEvalAllowed(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

      public boolean isPolyglotEvalAllowed(LanguageInfo targetLanguage)
      Returns true if the current language is allowed to evaluate guest application provided code of the given language, else false. If this method returns true then the current language has permission to use parsePublic(Source, String...) and getScopePublic(LanguageInfo) for the given language. If the given language is null then this method will return true if polyglot access is allowed in principle, else false. Languages may want to call this method twice. Once with null 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()
      Returns 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 getPolyglotBindings(), importSymbol(String) or exportSymbol(String, Object) fails with a SecurityException.
      Since:
      19.2
      See Also:
    • isMimeTypeSupported

      public boolean isMimeTypeSupported(String mimeType)
      Allows it to be determined if this Context 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

      public CallTarget parseInternal(Source source, String... argumentNames)
      Parses the source of a public or internal language and returns the parse result as 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...).

      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. Use parsePublic(Source, String...) for that purpose instead. Compared to 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 parsePublic(Source, String...) as it contains code provided by the guest language user. Parsing regular expressions with the internal regular expression engine should call parseInternal(Source, String...) instead, as this is considered an implementation detail of the language.

      It is recommended that the language uses parsePublic(Source, String...) or 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.

      Parameters:
      source - the source to evaluate
      argumentNames - the names of CallTarget.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 a public language nor an internal language.
      IllegalArgumentException - if the language is not allowed to evaluate code by the current language
      Since:
      19.2
      See Also:
    • parsePublic

      public CallTarget parsePublic(Source source, String... argumentNames)
      Parses the source of a public language and returns the parse result as 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...).

      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 to parsePublic(Source, String...) as it contains code provided by the guest language user. Parsing regular expressions with the internal regular expression engine should call parseInternal(Source, String...) instead, as this is considered an implementation detail of the language.

      It is recommended that the language uses parsePublic(Source, String...) or 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.

      Languages should check for eval permissions for each public language prior to calling this method, otherwise IllegalArgumentException is thrown if not sufficient privileges are available.

      Parameters:
      source - the source to evaluate
      argumentNames - the names of CallTarget.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 a public language
      IllegalArgumentException - if the language is not allowed to evaluate code by the current language
      Since:
      19.2
      See Also:
    • in

      public InputStream in()
      Input stream provided by Context.Builder.in(InputStream) this language is being executed in.
      Returns:
      reader, never null
      Since:
      0.8 or earlier
    • out

      public OutputStream out()
      Standard output writer provided by Context.Builder.out(OutputStream) this language is being executed in.
      Returns:
      writer, never null
      Since:
      0.8 or earlier
    • err

      public OutputStream err()
      Standard error writer provided by Context.Builder.err(OutputStream) this language is being executed in.
      Returns:
      writer, never null
      Since:
      0.8 or earlier
    • lookup

      public <T> T lookup(Class<T> type)
      Looks additional service up. An environment for a particular 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.
      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

      public <S> S lookup(InstrumentInfo instrument, Class<S> type)
      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 query
      type - the class of the requested type
      Returns:
      the registered service or null if none is found
      Since:
      0.26
    • lookup

      public <S> S lookup(LanguageInfo language, Class<S> type)
      Returns an additional service provided by the given language, specified by type. For services registered by 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.
      Type Parameters:
      S - the requested type
      Parameters:
      language - the language to query
      type - 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

      public boolean initializeLanguage(LanguageInfo targetLanguage)
      Ensures that the target language is initialized. This method firstly verifies that the target language is accessible from this language. If not the SecurityException is thrown. Then the target language initialization is performed if not already done.
      Parameters:
      targetLanguage - the language to initialize
      Throws:
      SecurityException - if an access to targetLanguage is not permitted
      Since:
      20.1.0
    • getInternalLanguages

      public Map<String,LanguageInfo> getInternalLanguages()
      Returns all languages that are installed and internally accessible in the environment. Using the language instance additional services can be looked 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

      public LanguageInfo getHostLanguage()
      Retrieves the host language used in this environment. The returned language can be used to obtain the host language top scope object using getScopeInternal(LanguageInfo) method.
      Since:
      24.2
    • getPublicLanguages

      public Map<String,LanguageInfo> getPublicLanguages()
      Returns all languages that are installed and publicly accessible in the environment. Using the language instance additional services can be looked 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

      public LanguageInfo getLanguageInfo(Class<? extends TruffleLanguage<?>> languageClass)
      Returns the language info for a given language class if available. The class may be obtained with InteropLibrary.getLanguage(Object). Throws an IllegalArgumentException 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

      public Map<String,InstrumentInfo> 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 be looked up .
      Since:
      0.26
    • getTimeZone

      public ZoneId getTimeZone()
      Returns the default time zone of this environment. If the time-zone was not explicitly set by the embedder then the system default time-zone will be returned.
      Since:
      19.2
      See Also:
    • getConfig

      public Map<String,Object> getConfig()
      Configuration arguments passed from an outer language context to an inner language context. Inner language contexts can be created using newInnerContextBuilder(String...).
      Since:
      0.11
      See Also:
    • getContext

      public TruffleContext getContext()
      Returns the polyglot context associated with this environment.
      Returns:
      the polyglot context
      Since:
      0.30
    • isPreInitialization

      public boolean isPreInitialization()
      Returns true if this Context is being pre-initialized. For a given environment, the return value of this method never changes.
      Since:
      19.0
      See Also:
    • getPublicTruffleFile

      public TruffleFile getPublicTruffleFile(String path)
      Returns a 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.
      Parameters:
      path - the absolute or relative path to create TruffleFile for
      Returns:
      TruffleFile
      Throws:
      UnsupportedOperationException - when the FileSystem supports only URI
      IllegalArgumentException - if the path string cannot be converted to a Path
      Since:
      19.3.0
      See Also:
    • getPublicTruffleFile

      public TruffleFile getPublicTruffleFile(URI uri)
      Returns a TruffleFile for given path. See getPublicTruffleFile(String) for detailed information.
      Parameters:
      uri - the URI to create TruffleFile for
      Returns:
      TruffleFile
      Throws:
      UnsupportedOperationException - when URI scheme is not supported
      IllegalArgumentException - if preconditions on the uri do not hold.
      FileSystemNotFoundException - is the file system, identified by the uri, does not exist and cannot be created automatically
      Since:
      19.3.0
    • getInternalTruffleFile

      public TruffleFile getInternalTruffleFile(String path)
      Returns a 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 getTruffleFileInternal(String, Predicate) and perform the language standard libraries check using a predicate.
      Parameters:
      path - the absolute or relative path to create TruffleFile for
      Returns:
      TruffleFile
      Throws:
      UnsupportedOperationException - when the FileSystem supports only URI
      IllegalArgumentException - if the path string cannot be converted to a Path
      Since:
      19.3.0
      See Also:
    • getInternalTruffleFile

      public TruffleFile getInternalTruffleFile(URI uri)
      Returns TruffleFile for given URI. See getInternalTruffleFile(String) for detailed information.
      Parameters:
      uri - the URI to create TruffleFile for
      Returns:
      TruffleFile
      Throws:
      UnsupportedOperationException - when URI scheme is not supported
      IllegalArgumentException - if preconditions on the uri do not hold.
      FileSystemNotFoundException - is the file system, identified by the uri, does not exist and cannot be created automatically
      Since:
      19.3.0
      See Also:
    • getTruffleFileInternal

      public TruffleFile getTruffleFileInternal(String path, Predicate<TruffleFile> filter)
      Returns a 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:

      1. If the IO is enabled by the Context an accessible TruffleFile is returned without any other checks.
      2. If the given path does not locate a file in a language home a TruffleFile with no access is returned.
      3. If the given filter accepts the file a readable TruffleFile is returned. Otherwise, a TruffleFile with no access is returned.

      The relation to getPublicTruffleFile(String) and getInternalTruffleFile(String) is:

      Parameters:
      path - the absolute or relative path to create TruffleFile for
      filter - to enable read access to TruffleFile. Multiple invocations of filter.test(file) must consistently return true or consistently return false for a given path.
      Returns:
      TruffleFile
      Throws:
      UnsupportedOperationException - when the FileSystem supports only URI
      IllegalArgumentException - if the path string cannot be converted to a Path
      Since:
      21.1.0
      See Also:
    • getTruffleFileInternal

      public TruffleFile getTruffleFileInternal(URI uri, Predicate<TruffleFile> filter)
      Returns a TruffleFile for given URI. See getTruffleFileInternal(String, Predicate) for detailed information.
      Parameters:
      uri - the URI to create TruffleFile for
      filter - to enable read access to TruffleFile. Multiple invocations of filter.test(file) must consistently return true or consistently return false for a given path.
      Returns:
      TruffleFile
      Throws:
      UnsupportedOperationException - when the FileSystem supports only URI
      IllegalArgumentException - if preconditions on the uri do not hold.
      FileSystemNotFoundException - is the file system, identified by the uri, does not exist and cannot be created automatically
      Since:
      21.1.0
      See Also:
    • getCurrentWorkingDirectory

      public TruffleFile getCurrentWorkingDirectory()
      Gets the current working directory. The current working directory is used to resolve non absolute paths in TruffleFile methods.
      Returns:
      the current working directory
      Throws:
      SecurityException - if the filesystem denies reading of the current working directory
      Since:
      19.0
    • setCurrentWorkingDirectory

      public void setCurrentWorkingDirectory(TruffleFile currentWorkingDirectory)
      Sets the current working directory. The current working directory is used to resolve non absolute paths in TruffleFile methods.
      Parameters:
      currentWorkingDirectory - the new current working directory
      Throws:
      UnsupportedOperationException - if setting of the current working directory is not supported
      IllegalArgumentException - if the currentWorkingDirectory is not a valid current working directory
      SecurityException - if currentWorkingDirectory is not readable
      Since:
      19.0
    • getFileNameSeparator

      public String getFileNameSeparator()
      Returns the name separator used to separate names in TruffleFile's path string.
      Returns:
      the name separator
      Since:
      19.0
    • getPathSeparator

      public String 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

      public void registerService(Object service)
      Registers additional services provided by the language. The registered services are made available to users via 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.

      Parameters:
      service - a service to be returned from associated lookup method
      Throws:
      IllegalStateException - if the method is called outside of TruffleLanguage.createContext(com.oracle.truffle.api.TruffleLanguage.Env) method
      Since:
      19.0
    • isCreateProcessAllowed

      public boolean isCreateProcessAllowed()
      Returns true if the creation of a sub-process is allowed in the current environment.
      Since:
      19.1.0
      See Also:
    • newProcessBuilder

      public TruffleProcessBuilder newProcessBuilder(String... command)
      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

      public Map<String,String> getEnvironment()
      Returns an unmodifiable map of the process environment. When the 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.
      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 appropriate close method is invoked. Alternatively, a shutdown hook may be used to delete the file automatically.

      Parameters:
      dir - the directory in which the file should be created or null for a default temporary directory
      prefix - 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 used
      attrs - 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 error
      IllegalArgumentException - if the prefix or suffix cannot be used to generate a valid file name
      UnsupportedOperationException - if the attributes contain an attribute which cannot be set atomically or FileSystem does not support default temporary directory
      SecurityException - if the FileSystem 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 or null for a default temporary directory
      prefix - the prefix to generate the directory's name or null
      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 error
      IllegalArgumentException - if the prefix cannot be used to generate a valid file name
      UnsupportedOperationException - if the attributes contain an attribute which cannot be set atomically or FileSystem does not support default temporary directory
      SecurityException - if the FileSystem denied the operation
      Since:
      19.3.0
    • createHostAdapterClass

      @Deprecated(since="22.1") public Object createHostAdapterClass(Class<?>[] types)
      Deprecated.
      since 22.1; replaced by createHostAdapter(Object[]).
      Since:
      20.3.0
    • createHostAdapterClassWithStaticOverrides

      @Deprecated(since="22.1") public Object createHostAdapterClassWithStaticOverrides(Class<?>[] types, Object classOverrides)
      Deprecated.
      Since:
      20.3.0
    • createHostAdapter

      public 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. Implementations must be allowed for these types. The returned host adapter class is an instantiable host object that is also a meta object, so isMetaInstance 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 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);
       
       
      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 - if types is null
      Since:
      22.1
      See Also:
    • createHostAdapterWithClassOverrides

      public Object createHostAdapterWithClassOverrides(Object[] types, Object classOverrides)
      Like 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 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 either types or classOverrides is null.
      Since:
      22.1
      See Also:
    • getInternalResource

      public TruffleFile getInternalResource(Class<? extends InternalResource> resource) throws IOException
      Returns the TruffleFile representing the target directory of an internal resource. The internal resource is guaranteed to be fully InternalResource.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 - if resource is not associated with this language
      IOException - in case of IO error
      Since:
      23.1
    • getInternalResource

      public TruffleFile getInternalResource(String resourceId) throws IOException
      Returns the TruffleFile representing the target directory of an internal resource. Unlike the getInternalResource(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, see Engine.copyResources(Path, String...). If the resource with the specified resourceId is not associated to this language, the function returns null.
      Parameters:
      resourceId - unique id of the resource to be loaded
      Returns:
      internal resource directory or null if resource with the resourceId is not associated with this language
      Throws:
      IOException - in case of IO error
      Since:
      23.1
      See Also:
    • getLogger

      public TruffleLogger getLogger(String loggerName)
      Find or create a context-bound logger. The returned 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).

      Parameters:
      loggerName - the name of a TruffleLogger, if a loggerName is null or empty a root logger for language or instrument is returned
      Returns:
      a TruffleLogger
      Since:
      21.1
    • getLogger

      public TruffleLogger getLogger(Class<?> forClass)
      Find or create a context-bound logger. The returned 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).

      Parameters:
      forClass - the Class to create a logger for
      Returns:
      a TruffleLogger
      Since:
      21.1
    • submitThreadLocal

      public 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. If the threads array is 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.

      Parameters:
      threads - the threads to execute the action on. null for all threads
      action - the action to perform on that thread.
      Since:
      21.1
      See Also:
    • registerOnDispose

      public void registerOnDispose(Closeable closeable)
      Registers 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.

      Parameters:
      closeable - to be closed on context dispose.
      Since:
      21.2
    • getSandboxPolicy

      public SandboxPolicy getSandboxPolicy()
      Returns the context's 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.
      Since:
      23.0
      See Also:
    • getScopePublic

      public Object getScopePublic(LanguageInfo language) throws IllegalArgumentException
      Returns the scope object of a non-null public language. The returned value follows the contract of TruffleLanguage.getScope(Object) of the other language, therefore it must be an interop scope object and may have parent scopes. The bindings object exposes all top scopes variables as flattened members. In addition to being a scope the returned object may implement any number of the interop 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 with eval permissions are accessible. If a language is not accessible then an SecurityException 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 each public language prior to calling this method, otherwise it might cause SecurityException 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 entered
      SecurityException - if polyglot scope access is not enabled for this language.
      IllegalArgumentException
      Since:
      24.1
      See Also:
    • getScopeInternal

      public Object getScopeInternal(LanguageInfo language)
      Returns the scope object of a non-null internal language. Works the same as getScopePublic(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. Use getScopePublic(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 an internal 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 or dependent languages. For convenience, this method will also succeed for all accessible public languages with eval 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 entered
      SecurityException - if polyglot scope access is not enabled for this language.
      Since:
      24.1
      See Also: