Class NaftahPlayground

java.lang.Object
org.daiitech.naftah.playground.NaftahPlayground

public class NaftahPlayground extends Object
Browser-hosted runtime for the Naftah Playground.

This class provides the bridge between the Java-based Naftah runtime and the browser environment. It is intended to run under browser-hosted Java runtimes such as CheerpJ and exposes native methods that allow communication with JavaScript and the playground user interface.

The runtime is responsible for:

  • Initializing the playground environment.
  • Bootstrapping language metadata and class-scanning results.
  • Exposing the runtime instance to JavaScript.
  • Executing user-provided Naftah source code.
  • Reporting execution output and errors back to the browser.

Execution state is cleaned after each run to avoid stale parser state, thread-local leaks, and unintended cross-execution interactions.

Author:
Chakib Daii
  • Field Details

    • LOGGER

      public static final Logger LOGGER
      Logger used by the playground runtime.
    • NAFTAH_PLAYGROUND_LOG_LEVEL_PROPERTY

      private static final String NAFTAH_PLAYGROUND_LOG_LEVEL_PROPERTY
      System property used to configure the playground logging level.

      If defined, its value is passed to the logging subsystem during class initialization to determine the minimum log level emitted by the playground runtime.

      See Also:
    • NAFTAH_PLAYGROUND_USE_CLASSPATH_INDEX_PROPERTY

      private static final String NAFTAH_PLAYGROUND_USE_CLASSPATH_INDEX_PROPERTY
      System property used to enable or disable the classpath index in the playground.

      When set to true, the runtime will use the precomputed classpath index for faster lookup instead of performing full classpath scanning.

      If not defined, the default behavior is used.

      See Also:
    • NAFTAH_PLAYGROUND_USE_CLASSPATH_INDEX_FROM_JS_PROPERTY

      private static final String NAFTAH_PLAYGROUND_USE_CLASSPATH_INDEX_FROM_JS_PROPERTY
      System property key used to enable or disable usage of the classpath index when accessed from JavaScript (JS bridge context).

      When set to true, JavaScript-driven lookups will use the same precomputed classpath index for improved performance instead of falling back to dynamic resolution.

      If the property is not defined, the default behavior is used.

      See Also:
    • INDEX_CACHE_PATH

      public static final Path INDEX_CACHE_PATH
      Absolute file system path to the full runtime index cache used by the playground.

      This value is resolved during static initialization and points to the precomputed index file used to accelerate class and function lookups.

    • MINIMAL_INDEX_CACHE_PATH

      public static final Path MINIMAL_INDEX_CACHE_PATH
      Absolute file system path to the minimal runtime index cache used by the playground.

      The minimal index is a lightweight version of the full runtime index, optimized for reduced memory footprint and faster startup times.

    • CACHE_LOAD_ASYNC_PROPERTY

      public static final String CACHE_LOAD_ASYNC_PROPERTY
      System property used to control asynchronous cache loading behavior.

      If defined and enabled, cache entries may be loaded asynchronously, allowing cache population to occur in the background without blocking the calling thread. If not specified, the default cache loading behavior configured by the runtime is used.

      See Also:
    • BOOTSTRAPPING

      private static volatile boolean BOOTSTRAPPING
      Indicates whether the system is currently in the bootstrap phase.

      When true, certain runtime behaviors may be restricted or handled differently to support safe initialization.

      This field is volatile to ensure visibility across threads.

  • Constructor Details

    • NaftahPlayground

      public NaftahPlayground()
  • Method Details

    • sendToHTML

      public static void sendToHTML(String s)
      Sends text to the playground output area in the browser.

      This method is implemented by the JavaScript host environment and is used to display execution results, diagnostic information, and error messages to the user.

      Parameters:
      s - text to display
    • sendToLog

      public static void sendToLog(String s)
      Sends a message to the browser-side logging system.

      This method is implemented by the JavaScript host and is intended for low-level diagnostics and debugging output.

      Parameters:
      s - message to log
    • nativeSetApplication

      public static void nativeSetApplication(NaftahPlayground app)
      Registers the playground runtime instance with the browser environment.

      The JavaScript host uses this method to obtain a reference to the running playground instance so that browser code can invoke methods such as run(String).

      Parameters:
      app - the playground runtime instance
    • setBootstrapState

      public static void setBootstrapState(String state)
      Updates the bootstrap state visible to the browser UI.

      This method is implemented by the JavaScript host and allows the runtime to communicate its initialization progress.

      Parameters:
      state - the current runtime state
    • loadIndexObject

      public static JSObject loadIndexObject()
      Loads and returns the JavaScript-based index object from the host environment.

      This method is implemented natively in the JavaScript bridge and provides access to the precomputed index structure used by the runtime for faster lookup and resolution.

      Returns:
      a JSObject representing the loaded index object
    • main

      public static void main(String[] args)
      Initializes and starts the playground runtime.

      This method performs the following steps:

      1. Creates and exposes the runtime instance to JavaScript.
      2. Configures runtime and scanning properties.
      3. Loads cached class-scanning metadata.
      4. Bootstraps built-in functions and accessible classes.
      5. Publishes bootstrap status updates to the browser UI.

      If initialization fails, the runtime enters the NaftahPlayground.RuntimeState.FAILED state and logs diagnostic information.

      Parameters:
      args - command-line arguments; ignored
    • bootstrap

      private static void bootstrap()
      Bootstraps the Naftah playground runtime.

      This method initializes system properties required for execution, loads class scanning metadata from either the minimal or full cache, and prepares the runtime environment for executing Naftah code.

      Bootstrap phases:

      1. Configure runtime system properties (JDK scanning, caching, word chunking).
      2. Determine whether full classpath scanning should be used.
      3. Load class scanning metadata from cache (minimal or full).
      4. Initialize the playground runtime via bootstrapPlayground.
      5. Log runtime metadata for debugging purposes.
      6. Signal final runtime state (READY or FAILED).

      The method is designed to run once during application startup. It is not thread-safe and should not be invoked concurrently.

      If any error occurs during initialization, the runtime is placed in NaftahPlayground.RuntimeState.FAILED state and diagnostic information is logged. Regardless of success or failure, a final "bootstrap done" message is emitted.

      Performance note: loading and parsing the class scanning cache can be expensive in browser environments (e.g., CheerpJ), especially when using the full cache. Consider using the minimal cache for faster startup.

    • run

      public String run(String code)
      Executes a snippet of Naftah source code.

      The provided code is parsed, evaluated, and its result is returned. If the result is printable, it is also sent to the browser output area. Variable declarations and None values do not produce output.

      Any exception thrown during parsing or execution is converted into a stack trace, displayed in the browser, and returned to the caller.

      Regardless of success or failure, parser state, execution context, and thread-local resources are cleared before returning.

      Parameters:
      code - the Naftah source code to execute
      Returns:
      the execution result as a string; an empty string if no output is produced; or the exception stack trace if execution fails