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 scriptMyLangKernelextendsKernelMainBase: it lives in the page, creates the worker and turns its messages into Basthon's events. It mostly describes the language.MyLangKernelWorkerextendsKernelWorkerBase: it runs the code with the language's runtime (usually compiled to WebAssembly).comlink-worker.tsexposes the worker class to the main thread:
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
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
}
}newWorkermust create the worker withsandboxed: true: this is what gives it an opaque origin.workerOptionsgives the worker's constructor its options (the kernel's options by default): override it to add your own.- Evaluations, files, completion and the
morecheck are forwarded to the worker: nothing else to write here.
The worker side
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
.wasmfile imported as a URL (await import("sql.js/dist/sql-wasm.wasm")in the SQL kernel, see theasset/resourcerule ofpackages/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)andthis.sendStderrStream(data, text)(always passdata: it tells the frontend which evaluation the output belongs to); - result: a MIME bundle (
{ "text/plain": "42" }, withtext/html,image/svg+xml... if you have them), orundefinedif the code has no value; - errors: throw a
KernelError(name, value, traceback, displayed). If the runtime already printed the error on stderr, setdisplayedtotrueso that it is not printed twice. Any other exception is printed byKernelWorkerBase.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:
| Feature | Method |
|---|---|
read an input (input(), scanf...) | input(prompt, password): blocks until the answer; throws InputInterruptedError or InputEOFError |
| wait | sleep(seconds) |
display a MIME bundle (or an OffscreenCanvas, as an image) | display(bundle), e.g. display({ "image/svg+xml": svg }) |
| clear the output | clearOutput(wait) |
| download a file | download(bytes, filename), downloadSVGAsPNG(svg, filename, scale) |
| interactive output (p5, figures...) | displayKernelIFrame(html, fallback): returns the MessagePort to the iframe |
| drawing with mouse and keyboard events | createCanvas(width, height), displayLiveCanvas(canvas) |
| camera, sound | openCamera(constraints), openAudio(options) |
| self-assessment | logValidation(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 themoduleExtsextensions.more(code): is the code incomplete? The console then asks for a continuation line. Returnfalseif you can't tell.complete(code): completions of the last word,[completions, start]or[]. Ask the language when it has a completer (Python'srlcompleter, R'sutils), otherwise list its names (the keywords, the user's variables, the builtins: SQLite'spragma_function_list, Giac's commands generated bykernel-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 acaseinKernelLoader's constructor (a dynamicimport, so that the kernel is in its own chunk) and the dependency inpackage.json. The browser bundle then includes it. basthoncommand (packages/kernel-node/): a worker scriptsrc/mylang-worker.ts(importing./worker-globalsfirst, then exposing the worker class fromlib/worker), the language in the webpack entries (bundler/webpack.config.ts), inKERNELSand inKERNEL_EXTENSIONS(src/kernels.ts).- Tests: the language in
NODE_KERNELSandBROWSER_KERNELS(tests/lib/fixtures.ts), and atests/mylang_base.test.ts(running code, errors, inputs, files, modules; see the other kernels' ones). Tests run in Node.js by default; usedescribeBrowsersfor 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 ofwww/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
- [ ]
newWorkercreates the worker withsandboxed: 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.