Skip to content

Writing a new kernel ​

A kernel runs the code of one language. This page shows what a new one must implement, and where to register it. Read Architecture and security first: a kernel runs in an opaque origin worker, and the page never trusts what it sends.

The classes and methods named here are described in the kernel JavaScript API, generated from the code: KernelBase, KernelMainBase and KernelWorkerBase.

The two halves of a kernel ​

A kernel is a package packages/kernel-<language>/ (named @basthon/kernel-<language>), depending on @basthon/kernel-base:

packages/kernel-mylang/
  package.json          # build: tsc, dependencies: @basthon/kernel-base, the runtime
  tsconfig.json         # as the other kernels'
  src/
    index.ts            # export * from "./kernel";
    kernel.ts           # MyLangKernel: the main thread side
    worker.ts           # MyLangKernelWorker: the worker side
    comlink-worker.ts   # the worker's script
  • MyLangKernel extends KernelMainBase: it lives in the page, creates the worker and turns its messages into Basthon's events. It mostly describes the language.
  • MyLangKernelWorker extends KernelWorkerBase: it runs the code with the language's runtime (usually compiled to WebAssembly).
  • comlink-worker.ts exposes the worker class to the main thread:
ts
import { expose } from "@basthon/kernel-base/worker";
import { MyLangKernelWorker } from "./worker";

expose(MyLangKernelWorker);

The smallest kernel, packages/kernel-echo/, extends KernelBase directly and prints the code it is given, without a worker: it is only meant to test frontends. A real kernel always runs in a worker. The JavaScript kernel (packages/kernel-javascript/) is the simplest one to read.

The main thread side ​

ts
import { KernelMainBase } from "@basthon/kernel-base/worker";
import type { KernelOptions } from "@basthon/kernel-base";
import { MyLangKernelWorker } from "./worker";

export class MyLangKernel extends KernelMainBase<MyLangKernelWorker> {
  constructor(options: KernelOptions) {
    super(options);
  }

  protected newWorker(): Worker {
    return new Worker(new URL("./comlink-worker.js", import.meta.url), {
      //@ts-ignore
      sandboxed: true, // removing this line will cause security issues
    });
  }

  public language() {
    return "mylang"; // as in the kernel URL parameter
  }

  public languageName() {
    return "MyLang"; // as displayed
  }

  public moduleExts() {
    return ["ml"]; // extensions of the files installed by putModule
  }

  public ps1() {
    return "  ml> "; // the console's prompt
  }

  public ps2() {
    return "...> "; // the continuation prompt
  }
}
  • newWorker must create the worker with sandboxed: true: this is what gives it an opaque origin.
  • workerOptions gives the worker's constructor its options (the kernel's options by default): override it to add your own.
  • Evaluations, files, completion and the more check are forwarded to the worker: nothing else to write here.

The worker side ​

ts
import { KernelWorkerBase, KernelError } from "@basthon/kernel-base/worker";

export class MyLangKernelWorker extends KernelWorkerBase {
  constructor(options?: any) {
    // do not forget to call the parent constructor
    super(options);
  }

  public language() {
    return "mylang";
  }

  // load the runtime, once
  protected async _init(): Promise<void> {
    ...
  }

  // run code: print with sendStdoutStream/sendStderrStream,
  // return a MIME bundle or undefined
  protected async _eval(data: any, code: string) {
    ...
  }

  public putFile(filename: string, content: ArrayBuffer) { ... }
  public putModule(filename: string, content: ArrayBuffer) { ... }
  public async more(code: string): Promise<boolean> { ... }
  public async complete(code: string): Promise<[string[], number] | []> { ... }
}

Loading the runtime: _init ​

_init is called once, when the kernel starts. The runtime's files (WebAssembly modules, libraries) are fetched by the worker:

  • files imported by the code are emitted by the bundler next to the worker, e.g. a .wasm file imported as a URL (await import("sql.js/dist/sql-wasm.wasm") in the SQL kernel, see the asset/resource rule of packages/browser-bundle/bundler/);
  • bigger files can be served from basthonRoot(), the kernel's directory (<rootPath>/<version>/<language>/), or from a CDN.

Requests to the site go through the proxy worker, which only serves the assets directory, without credentials (see the architecture page).

Running code: _eval ​

An evaluation goes through both halves; your code is only _eval (and the runtime it calls):

_eval(data, code) runs the code and returns its result:

  • outputs: this.sendStdoutStream(data, text) and this.sendStderrStream(data, text) (always pass data: it tells the frontend which evaluation the output belongs to);
  • result: a MIME bundle ({ "text/plain": "42" }, with text/html, image/svg+xml... if you have them), or undefined if the code has no value;
  • errors: throw a KernelError(name, value, traceback, displayed). If the runtime already printed the error on stderr, set displayed to true so that it is not printed twice. Any other exception is printed by KernelWorkerBase.eval.

An evaluation ends when _eval returns and the promises given to addEvalPromise are settled (e.g. an animation started by the code).

What the worker gives the code ​

KernelWorkerBase implements the features that need the page; call them from the runtime's bindings:

FeatureMethod
read an input (input(), scanf...)input(prompt, password): blocks until the answer; throws InputInterruptedError or InputEOFError
waitsleep(seconds)
display a MIME bundle (or an OffscreenCanvas, as an image)display(bundle), e.g. display({ "image/svg+xml": svg })
clear the outputclearOutput(wait)
download a filedownload(bytes, filename), downloadSVGAsPNG(svg, filename, scale)
interactive output (p5, figures...)displayKernelIFrame(html, fallback): returns the MessagePort to the iframe
drawing with mouse and keyboard eventscreateCanvas(width, height), displayLiveCanvas(canvas)
camera, soundopenCamera(constraints), openAudio(options)
self-assessmentlogValidation(data), _breakpointMoveOn() (internal: kept out of the API documentation)

The worker blocks while the code runs: input and sleep are synchronous (SharedArrayBuffer when the page is cross-origin isolated, Basthon's encrypted ephemeral API otherwise, see the architecture page).

Files, modules, completion ​

  • putFile(filename, content): write an auxiliary file in the runtime's virtual filesystem (in its working directory). A language without filesystem prints an error.
  • putModule(filename, content): install a user's module (loaded by the user's code), with one of the moduleExts extensions.
  • more(code): is the code incomplete? The console then asks for a continuation line. Return false if you can't tell.
  • complete(code): completions of the last word, [completions, start] or []. Ask the language when it has a completer (Python's rlcompleter, R's utils), otherwise list its names (the keywords, the user's variables, the builtins: SQLite's pragma_function_list, Giac's commands generated by kernel-xcas' yarn update-commands).

The frontends put the files and modules again after a restart: the worker doesn't need to keep them.

Registering the kernel ​

  • Kernel loader (packages/kernel-loader/): add a case in KernelLoader's constructor (a dynamic import, so that the kernel is in its own chunk) and the dependency in package.json. The browser bundle then includes it.
  • basthon command (packages/kernel-node/): a worker script src/mylang-worker.ts (importing ./worker-globals first, then exposing the worker class from lib/worker), the language in the webpack entries (bundler/webpack.config.ts), in KERNELS and in KERNEL_EXTENSIONS (src/kernels.ts).
  • Tests: the language in NODE_KERNELS and BROWSER_KERNELS (tests/lib/fixtures.ts), and a tests/mylang_base.test.ts (running code, errors, inputs, files, modules; see the other kernels' ones). Tests run in Node.js by default; use describeBrowsers for what needs a browser.
  • Documentation: a page www/docs/documentation/langages/mylang/ (in French: the user documentation), in the sidebar (www/.vitepress/config.mts) and in the table of www/docs/documentation/langages/index.md.
  • Frontends: the console and the notebook (their own repositories) need the language's name, its editor mode and its file extension.

Checklist ​

  • [ ] newWorker creates the worker with sandboxed: true.
  • [ ] Outputs pass the evaluation's data.
  • [ ] Errors already printed are thrown with displayed: true.
  • [ ] Inputs use input (they work with and without cross-origin isolation).
  • [ ] Nothing from the page is used by the worker (document, window): ask the main thread through the methods above.
  • [ ] Doc comments on every class and method (TSDoc, @param name - Description.), in English.
  • [ ] Tests in Node.js and in browsers.