# Adding a language

How to make a language playable: an editor with diagnostics, hover and completion, a Run
button, and any other outputs, in any page that uses these playgrounds. The protocol is
`docs/protocol.md`; this guide is the route through it.

Two complete examples, the same λ-calculus with five outputs. Copy one to start:

| Template | Server | Build |
|---|---|---|
| `templates/typescript/` | about 500 lines of TypeScript on `serve()` | `modules/templates/lambda-template.nix` |
| `templates/rust/` | about 900 lines of Rust and 20 of JavaScript, JSON-RPC by hand, with `cargo test` | `modules/templates/lambda-template-rust.nix` |

The templates are 0BSD: a copy owes nothing, not even a notice. Set the copy's `license` (in
`source.json`) to its own. A copy that imports `code-playgrounds/worker` or
`code-playgrounds/protocol` (MIT OR Apache-2.0) takes that licence for that dependency.

The ready-made languages, in `playgroundkit/languages`, are larger examples; its `docs/guide.md`
lists them by route.

## What you build

A **language package**, a directory:

| File | What |
|---|---|
| `source.json` | the manifest without hashes: id, name, extensions, grammar, workers, outputs, examples, licence |
| `<name>.tmLanguage.json` | a TextMate grammar |
| worker scripts and their files | your compiler, interpreter or checker, compiled for the browser |
| `examples/` | programs, each with the text its run prints (`.expected`) |

`lib.mkLanguage` turns it into a package (it adds hashes and sizes); `lib.checkLanguage` tests
it; `flakeModules.default` puts it on a site.

## 1. Choose a runtime

Your code runs in a Web Worker inside a sandboxed frame: no network, no storage, no
SharedArrayBuffer and so no threads. A WebAssembly feature that not every browser has (JSPI,
say) needs a variant without it to fall back to (protocol §3).

- **WebAssembly** if your toolchain compiles to it: Rust (`wasm32-unknown-unknown`,
  wasm-bindgen), OCaml (wasm_of_ocaml), Haskell (GHC's WebAssembly backend), C and C++
  (Emscripten or wasi-sdk).
- **JavaScript** otherwise, or as a fallback: TypeScript, js_of_ocaml, Scala.js.
- **One classic script per worker.** Chromium starts no module worker from the frame's
  `blob:` URL. Bundle to one file (Vite, esbuild) and load more with `importScripts` or
  `import()` of `self.playground.url(path)`.
- **No blocking reads.** Nothing can block waiting for input. A server that reads stdin must
  instead take messages from a function your glue calls, as Koka's does
  (`docs/plan.md` D7).

A ready-made package on the same route as yours, in `playgroundkit/languages`, is the best
example after the templates (its guide lists them by route). Most put the language server and the runner in two workers, so a long run never holds the
editor.

## 2. Speak the protocol

Each message, both ways, is one JSON-RPC 2.0 message as a string, through `postMessage`.

| You receive | You answer |
|---|---|
| `initialize` | your LSP capabilities, plus `experimental.playground = { version: 1, outputs }` |
| `textDocument/didOpen`, `didChange`, `didClose` | nothing; publish `textDocument/publishDiagnostics` |
| `textDocument/hover`, `completion`, … | as LSP says |
| `playground/produce { output, textDocument, trigger, range?, context? }` | `{ status, items }`; stream earlier items with `playground/items` |
| `$/cancelRequest` | stop if you can; the host restarts you after a timeout anyway |

**Items** are typed: `text/plain`, `text/x-ansi` (stdout and stderr), `code` (highlighted
by a grammar), `tree`, `graph`, `table`, `diagnostics`, `verdicts`, `image/svg+xml`. The
host draws them in the page's style. Prefer them to a renderer of your own.

**In TypeScript**, `serve()` does all of this: you write the handlers
(`templates/typescript/src/server.ts`). Import it from `code-playgrounds/worker`, and the protocol's
types from `code-playgrounds/protocol`: the npm package, installed as the README's "In an npm
build" says. In this repository they are `packages/worker` and `packages/protocol`, which the
templates import by path.

- `diagnose`, `hover` and `completion` answer the editor; `produce` has one function per
  output; `action`, `release` and `reset` serve items with `ref` and `actions`.
- Any other LSP request (inlay hints, signature help, semantic tokens) goes in `requests`, by
  method, with its capability in `capabilities`.
- A produce function gets the `document`, the `trigger`, `range`, `context`, `args` and
  `firstLine`, streams with `emit(items)`, announces steps with `step(name)`, and sees a cancel
  on `signal`. It returns a status, or a status and items.

**In another language**, write a function `handle(message: string)` and a JavaScript
glue of a few lines:

```js
self.addEventListener("message", (e) => instance.handle(e.data));
// and from your code: self.postMessage(responseString)
```

- Rust: `templates/rust`. `Worker::handle(&mut self, message: &str) -> Vec<String>`
  returns the messages to post, so the server has no I/O and `cargo test` drives it;
  `glue.js` posts them.
- OCaml: `Js_of_ocaml.Js.export`, or the toplevel's own glue (`languages/ocaml` in `playgroundkit/languages`).
- Haskell: `foreign export javascript "handle"` with GHC's JSFFI (`languages/haskell` there).

## 3. Your files

Before your entry runs, the frame's bootstrap gives the worker its world:
- `fetch("path/in/package")` answers your package's files, and only those.
- `self.playground.url(path)` is a `blob:` URL of a file, for a loader that wants a URL.
- `self.playground.starting(promise)` holds readiness, if your loader finishes
  asynchronously.

`self.location` is a `blob:` URL. Never build a file's URL from it.

## 4. A grammar

A TextMate grammar colours your code everywhere: the editor before anything loads, static
pages (Shiki), apps, and VS Code. Use the conventional scope names (`keyword.control`,
`keyword.operator`, `string.quoted`, `comment.line`, `entity.name.function`,
`variable.parameter.function`). A parameter is `variable.parameter.function`: the host colours
that, and not the shorter `variable.parameter`.

**No `markup.*` scopes.** A theme gives `markup.underline`, `markup.italic` and `markup.inserted`
the styles of prose (underline, italics, strings, diff colours). A grammar that borrows them to
get a colour makes parameters look like strings in italics. The kit warns of every `markup.*`
scope.

Regular expressions must work under Shiki's JavaScript engine. The kit checks every rule and
tokenizes every example.

### Word characters

`editor.wordChars` in the manifest lists the characters a word has besides letters, digits and
`_`: Koka's `-'?`, OCaml's `'`. The word at the cursor, which completion filters by, and word
motions (Ctrl+arrow, double click) then treat `foo-bar` or `x'` as one word. Without it,
completing `foo-ba` offers nothing for `foo-bar`, because the word under the cursor is `ba`.
Give only the characters an identifier really has: letters, digits, `_` and whitespace are not
allowed. The kit's `wordCompletion` option checks it (below).

## 5. Build it with Nix

Build the workers as your project builds anything: `templates/typescript/build.ts` bundles
the server into one classic script with Vite; `modules/templates/lambda-template-rust.nix`
builds the Rust template with crane and rust-overlay (inputs your flake then needs too).
A package references no store path (a copy of the built directory then moves nothing else), and
`lib.mkLanguage` fails the build if one does. Set `resolve: { preserveSymlinks: true }` in a Vite
build, whose module comments name the store path that `node_modules` links to, and pass
`lib.rustRemapFlags { toolchain, cargoVendorDir }` as `CARGO_BUILD_RUSTFLAGS` in a Rust build,
whose panic locations name the toolchain and the vendored crates (D74).
Then, in your project's flake, with this repository as an input `playgrounds`:

```nix
packages.my-language = inputs.playgrounds.lib.mkLanguage pkgs {
  id = "my-language";
  src = myWorkers;                       # a derivation with the files source.json lists
  source = lib.importJSON ./playground/source.json;
};
checks.my-language-playground = inputs.playgrounds.lib.checkLanguage pkgs
  config.packages.my-language {
    diagnostic.text = "an erroneous program";
    invalid.text = "a program that does not parse";
    hover = { text = "a program"; line = 0; character = 4; contains = "its type"; };
    completion = { text = "pre"; line = 0; character = 3; label = "prelude"; };
  };
```

To offer the package to other flakes as a module, see "From your project's flake" below
(`lib.mkLanguageModule`, `lib.checkFlakeModule`).

### The conformance kit

`checkLanguage` runs the conformance kit under Node.js; `playgrounds check <package-dir>
[options.json]` runs it on a built package, with the same options as JSON. `lib.checkLanguageRemote`
and `playgrounds check <package-dir> --engines <dir>` run the same checks with every worker hosted
by a remote (`docs/protocol.md` §8); `--remote <url>` does it against a remote that is running.
It checks:
- the manifest, the files and the grammar (a warning for each `markup.*` scope);
- `initialize`;
- diagnostics, hover and completion, and with their options inlay hints, signature help,
  definition and word completion;
- every output on every example, once for each trigger it declares, with the example's hidden
  parts composed as a host does; the text of the outputs Run produces against the example's
  `expected` text, and each output's printed text against its `expectedOutputs` file;
- with `invalid`, that each `change` output answers a document it cannot be produced from with
  status `error` and its reason (protocol §5.2);
- cancellation;
- that the worker requested nothing outside its files.

| Option | Needs | Passes when |
|---|---|---|
| `diagnostic` | `text` | the server reports at least one diagnostic |
| `invalid` | `text` | every `change` output answers it with `error` and items. Usually the same text as `diagnostic.text`: a document the package cannot parse. |
| `hover` | `text`, `line`, `character`, `contains` | the hover's **plain text** (fences removed) contains `contains` |
| `completion` | `text`, `line`, `character`, `label` | the completion list has an item `label` |
| `inlayHints` | `text`, `range?`, `contains` | a hint's label contains `contains` |
| `signatureHelp` | `text`, `line`, `character`, `contains` | a signature's label contains `contains` |
| `definition` | `text`, `line`, `character`, `target?` | the server gives a place, starting at `target` (`{ line, character? }`) if given |
| `wordCompletion` | `text`, `line`, `character`, `label` | the manifest has `editor.wordChars`, `label` has one of them, and completion offers `label` |

An example in the manifest takes `expected` (the text of what Run prints), `expectedOutputs`
(`{ <output id>: path }`, the output's text in the form `itemsToText` prints, protocol §5.3; for
an output of any trigger), `status`, and the hidden parts `setup`, `prelude` and `tests`. The
kit composes the document (`composeDocument`), sends `firstLine`, and passes the tests in
`context`, so an example with a hidden setup is checked as a page would run it.

`playgrounds check <package-dir> --update <examples-dir>` writes the files it would compare
(`expected`, `expectedOutputs`) into `<examples-dir>`, named relative to their example's
directory, instead of comparing them. Review the diff, then commit. In a flake, run it from an app
(`nix run .#<id>-expected`), never as a check.

## 6. Put it on a site

A site whose flake imports `flakeModules.default`:

```nix
perSystem = { inputs', ... }: {
  playgrounds.languages.my-language.package = inputs'.my-language.packages.my-language;
};
```

On a page:

```html
<code-playground language="my-language">your example</code-playground>
```

`playgrounds.languages.<name>` is one language of the directory: `package` (a package from
`lib.mkLanguage` or another flake) or `engine` (a built-in engine, by default the name itself,
with its arguments); `enable` is on when either is set. `playgrounds.custom.<name>` is the
old form of `package`, kept for one release. `packages.playgrounds` is the directory and
`checks.playgrounds` checks it: it builds, its index lists a valid manifest for each
package, every blob is there, and no id or alias names two. The directory holds each file as
`blobs/<sha256>.<ext>` and no base; `playgrounds.site` (a built site) adds
`checks.playgrounds-site`, which verifies the site's headers as its host serves them
(`lib.checkSite`, docs/hosts.md).

### From your project's flake

A project that makes a language, or a library for a built-in one, exports a flake-parts
module; a site imports it beside `flakeModules.default`, and gets the language without
naming its package.

```nix
# The project's flake: the module for a language of its own...
flake.flakeModules.playgrounds = inputs.playgrounds.lib.mkLanguageModule {
  id = "my-language";
  package = pkgs: self.packages.${pkgs.stdenv.hostPlatform.system}.my-language;
};
# ...and a check that a site importing it gets a package that passes the kit.
perSystem = { pkgs, ... }: {
  checks.my-language-module = inputs.playgrounds.lib.checkFlakeModule pkgs {
    module = self.flakeModules.playgrounds;
    id = "my-language";
  };
};
```

`package` is a package, `pkgs: package` or `{ <system> = package; }`. A module that adds
a library to an engine of `playgroundkit/languages` sets `playgrounds.languages.ocaml.libraries` itself, from
`withSystem` (the project's own, so the exported module reaches the project's packages from
the site's flake):

```nix
{ withSystem, ... }:
{
  flake.flakeModules.playgrounds-library = {
    perSystem = { system, ... }: {
      playgrounds.languages.ocaml.libraries =
        [ (withSystem system ({ config, ... }: config.packages.my-library)) ];
    };
  };
}
```

```nix
# The site's flake.
imports = [
  inputs.playgrounds.flakeModules.default
  inputs.my-project.flakeModules.playgrounds
];
perSystem.playgrounds.languages.ocaml = { enable = true; libraries = [ /* the site's own */ ]; };
```

### Engines

An **engine** is `pkgs: args: package`: the function that builds a package from arguments such as
`id`, `name`, `aliases`, `libraries` and `sources`. A flake that offers languages exports its
engines (`lib.mkEngine` makes one) and sets the registry of the module,
`perSystem.playgrounds.engines`, which is empty by default; `playgrounds.languages.<name>` then
builds `engine` (by default the name) from the registry with the arguments given. Several
packages from one engine, each under its own id, name and aliases, are several attributes of
`languages` with the same `engine`. Contributions to one language from several modules merge: a
list concatenates and an attribute set joins by name (two modules that set the same name, or the
same argument that is not a collection, are an error). `lib.renamePackage pkgs package { id;
name ? …; aliases ? [ ]; }` renames any package: it links the files and writes a new manifest,
whose `languageId` keeps the id the language server knows the language by.

`playgroundkit/languages` is such a flake, with its engines and what each takes.

### A site's own npm build

A site built with npm (Astro, say) installs the framework's npm package from the store:
`"code-playgrounds": "file:.playgrounds"` in its `package.json`, and in the flake

```nix
nodeModules = inputs.playgrounds.lib.mkNodeModules pkgs { npmRoot = ./.; };
```

where `npmRoot` holds the site's `package.json` and `package-lock.json`. `lib.npmOverrides
pkgs` is `{ packageSourceOverrides; env; }` for nixpkgs' `importNpmLock`, if the site builds
`node_modules` itself: it replaces the lock's `node_modules/code-playgrounds` by `packages.npm`,
installed as a copy (`npm_config_install_links`; a link into the store would find no
`node_modules` for the package's own imports). `lib.npmWorkersOverrides pkgs` is the same with `packages.npm-workers`, the package holding only
`code-playgrounds/protocol` and `/worker`: build the `node_modules` that bundles a language's
workers with it and a framework change to the UI leaves the language's derivation, and its
binary-cache entry, as it was (docs/plan.md D77; the lock still names the whole package).
`lib.checkLanguageInputs pkgs [ package… ]` is the check that a package reaches no other framework
file. To refresh the lock, link `nix build
.#npm` to `.playgrounds` and run `npm install` (the lock only). The link is a build input,
not source: put `.playgrounds` in the ignore lists of the site's linters, formatters and
version control (Biome: `"!!.playgrounds"` in `files.includes`; `tsconfig.json`:
`"exclude": [".playgrounds"]`).

## Browser tests of your package

`code-playgrounds/testing` (from the npm package) runs a built directory in a real browser, from any
project: it reads nothing but the directory it serves. The directory is what `packages.playgrounds`
builds (or `assemble` and `site`, docs/hosts.md) plus a page with the element.

```ts
// playwright.config.ts: serve the built directory, with the strict headers (or `none`, `site`)
webServer: { command: "node node_modules/code-playgrounds/testing/serve.js dist 4310 full", url: "http://127.0.0.1:4310/index.json" },
```

```ts
import { playground } from "code-playgrounds/testing";

test("runs", async ({ page }) => {
  await page.goto("http://127.0.0.1:4310/index.html");
  const p = playground(page); // the page's first <code-playground>; or playground(page, "#id")
  await p.ready();
  await p.setCode('print("hi")');
  expect((await p.run("run")).status).toBe("ok");
  expect((await p.diagnostics()).length).toBe(0);
});
```

`startTestServer({ dir, mode })` does the same from a test's own setup and returns the URL,
and `requests()` is what the page fetched since the last call (for a test that the sandbox
fetches nothing). The handle calls the element's public members only (docs/elements.md), so a
test written with it survives changes inside the framework.

## In your own repository

A language of your own lives in your project: its workers, grammar and examples, a flake
that builds the package with `lib.mkLanguage` and checks it with `lib.checkLanguage` (§5), and a
flake module a site imports (§6). The ready-made languages are the example, in
`playgroundkit/languages`: its guide says what each one touches. The framework offers what a
language's own checks need as `code-playgrounds/conformance` (the engine, client, router and
node-worker helpers the kit uses), the `playgrounds` command, and `code-playgrounds/testing` for
the browser (below).

## Checking a site's cells and exercises

A site that keeps its code cells and exercises in files can have its flake prove that they
behave, in each worker variant of the built package, under Node:

```nix
checks.cells = inputs.playgrounds.lib.checkExercises pkgs {
  package = config.packages.my-language; # a built language package
  src = ./cells;
};
```

Under `src`, a file with one of the package's extensions is a **cell**: every output that runs
on Run must answer `ok` with no error or warning item. A directory holding `template.<ext>` and
`solution.<ext>`, and optionally `setup.<ext>`, `prelude.<ext>` and `tests.<ext>`, is an
**exercise**. The `mode` says what is checked, and is never guessed from a file that is
missing:

- `mode = "tests"` (the default): a `tests` file is required. The template must compile and fail
  every verdict of the `output` (default `check`), the solution must pass every one. The tests
  are a `context` file of role `tests`.
- `mode = "gaps"`: no tests file. The template must run (its Run outputs answer `ok`, even with
  warnings), and the solution must run clean, as a cell does.

```nix
checks.gaps = inputs.playgrounds.lib.checkExercises pkgs {
  package = config.packages.my-language;
  src = ./gap-exercises;
  mode = "gaps";      # output = "verdicts" names another output for the tests
};
```

Setup and prelude go at the start of the document as the host composes it (`composeDocument`,
protocol §4.2): each closed by the manifest's `document.terminator`, if it has one, and the
request carries `firstLine`, the line where the code starts. `playgrounds compose <package-dir>
--exercise <dir> [--part solution]` prints that document, so a failing exercise can be run by
hand.

Without Nix: `playgrounds exercises <package-dir> <dir> [--output <id>] [--mode tests|gaps]`
(or `node packages/conformance/exercises.ts …`, and `code-playgrounds/exercises` from the npm
package). It names each failing cell or exercise and why, and exits 1.

## Checklist

- [ ] Every worker is one classic script and loads its files through the world.
- [ ] `initialize` answers the manifest's outputs exactly.
- [ ] An output declares at least one trigger, and `needs` only with `demand`.
- [ ] A language whose phrases end with a token (OCaml's `;;`) declares it as
      `document.terminator`, so a hidden setup is a closed phrase.
- [ ] Each `run` starts fresh; a runaway program is the host's timeout, not a hang of the
      editor (put the language server in a worker of its own if runs can be long).
- [ ] A worker that runs a program in steps (a toplevel's phrases, a check's properties)
      announces each with `step(name)` (`playground/progress`): the time limit then applies to
      each step, and a timeout names it. One that reads `firstLine` counts its own line numbers
      from the reader's code.
- [ ] Positions are UTF-16 code units, as LSP and the editor count.
- [ ] The grammar passes the kit; examples cover an error (`"status": "error"`).
- [ ] No file in the built package is over 25 MiB: `assemble` stores a larger one as parts,
      which the host joins, so the worker sees it whole. Cloudflare Workers static assets accept
      no larger file. A worker entry script must stay under the limit.
- [ ] Nothing to do for size on a static host: `assemble` gzips every file whose extension
      hosts do not compress (anything but `.js`, `.mjs`, `.json`, `.wasm`, `.html`, `.css`,
      `.svg`, `.txt`, `.map`) when that saves 10 %, and the host decodes it, so the worker reads
      the original bytes. Data gzip barely shrinks is left alone.
      To keep a file as it is, give it one of those extensions.
- [ ] Every file's licence is compatible with the sites that will serve it, and `license` in
      `source.json` names each licence a file of the package is under.
