Bring your language
A language is a package: a manifest, a grammar and a worker. Here is one running beside its own files.
Framework decisions behind it: D1, D23, D32.
A small λ-calculus runs in the page, and the files that make it follow. They are read from the framework's template when this site is built, so they are the files of the package you are running.
The language, running
Edit the term and press Run. The editor colours it with the grammar, shows errors from the worker's language server, and the tabs are the outputs the manifest declares.
Its files
templates/typescript/source.json
The manifest: the language's name, extensions, outputs and workers.
Show the file
{
"id": "lambda-template",
"name": "λ-calculus",
"version": "1.0.0",
"description": "The untyped λ-calculus: normal forms, reduction steps, de Bruijn form, syntax trees and graphs. The TypeScript template.",
"aliases": ["lam"],
"extensions": [".lam"],
"grammar": { "scopeName": "source.lambda-template", "path": "lambda-template.tmLanguage.json" },
"editor": { "comments": { "line": "--" }, "brackets": [["(", ")"]], "indentUnit": " " },
"workers": [
{
"id": "server",
"serves": ["lsp", "outputs"],
"variants": [
{ "runtime": "js", "entry": "server.js", "files": ["server.js"], "policy": "wasm" }
]
}
],
"outputs": [
{
"id": "run",
"title": "Normal form",
"triggers": ["run"],
"kinds": [
"application/vnd.playground.code+json",
"text/plain",
"application/vnd.playground.diagnostics+json"
]
},
{
"id": "steps",
"title": "Steps",
"triggers": ["demand"],
"kinds": [
"application/vnd.playground.code+json",
"text/plain",
"application/vnd.playground.diagnostics+json"
]
},
{
"id": "debruijn",
"title": "De Bruijn",
"triggers": ["change"],
"kinds": [
"application/vnd.playground.code+json",
"application/vnd.playground.diagnostics+json"
]
},
{
"id": "tree",
"title": "Syntax tree",
"triggers": ["demand"],
"needs": "selection",
"kinds": [
"application/vnd.playground.tree+json",
"text/plain",
"application/vnd.playground.diagnostics+json"
]
},
{
"id": "graph",
"title": "Graph",
"triggers": ["demand"],
"kinds": [
"application/vnd.playground.graph+json",
"text/plain",
"application/vnd.playground.diagnostics+json"
]
}
],
"examples": [
{
"name": "Identity",
"path": "examples/identity.lam",
"expected": "examples/identity.expected"
},
{
"name": "Church numerals",
"path": "examples/church.lam",
"expected": "examples/church.expected"
},
{ "name": "A syntax error", "path": "examples/error.lam", "status": "error" }
],
"license": "0BSD AND (MIT OR Apache-2.0)"
}
templates/typescript/lambda-template.tmLanguage.json
The grammar, a TextMate grammar: it colours the editor.
Show the file
{
"name": "lambda-template",
"scopeName": "source.lambda-template",
"patterns": [
{ "match": "--.*$", "name": "comment.line.double-dash.lambda" },
{
"match": "^\\s*([A-Za-z0-9_']+)\\s*(=)",
"captures": {
"1": { "name": "entity.name.function.lambda" },
"2": { "name": "keyword.operator.assignment.lambda" }
}
},
{
"match": "([\\\\λ])\\s*([A-Za-z0-9_']+)\\s*(\\.)",
"captures": {
"1": { "name": "keyword.control.lambda" },
"2": { "name": "variable.parameter.lambda" },
"3": { "name": "punctuation.separator.lambda" }
}
},
{ "match": "[();]", "name": "punctuation.lambda" }
]
}
templates/typescript/src/server.ts
The worker: a language server and the outputs, on serve() from code-playgrounds/worker.
Show the file
// SPDX-License-Identifier: 0BSD
/**
* The λ-calculus's server: LSP for the editor and five outputs, on
* `packages/worker`'s `serve()`. Bundled into one classic worker script by
* build.ts. A language of your own starts from a copy of this directory;
* outside this repository it imports `code-playgrounds/worker` and
* `code-playgrounds/protocol` (the npm package) in place of these paths.
*/
import type { Item, Range } from "../../../packages/protocol/index.ts";
import { serve } from "../../../packages/worker/index.ts";
import {
deBruijn,
expand,
type Program,
parse,
ParseError,
type Span,
show,
step,
type Term,
unbound,
} from "./lambda.ts";
/** Steps `run` takes before it gives up, and steps `steps` shows. */
const LIMIT = 1000;
const SHOWN_STEPS = 50;
/** LSP positions (line, UTF-16 column) for offsets, and back. */
function lines(text: string) {
const starts = [0];
for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
return {
position(offset: number) {
let line = 0;
while (line + 1 < starts.length && (starts[line + 1] as number) <= offset) line++;
return { line, character: offset - (starts[line] as number) };
},
offset(p: { line: number; character: number }) {
return (starts[p.line] ?? text.length) + p.character;
},
};
}
const rangeOf = (text: string, span: Span): Range => {
const l = lines(text);
return { start: l.position(span.from), end: l.position(span.to) };
};
function parsed(text: string): Program | ParseError {
try {
return parse(text);
} catch (error) {
if (error instanceof ParseError) return error;
throw error;
}
}
/** The smallest subterm containing `from..to`. */
function at(t: Term, from: number, to: number): Term | undefined {
if (from < t.span.from || to > t.span.to) return undefined;
const children = t.kind === "lam" ? [t.body] : t.kind === "app" ? [t.fun, t.arg] : [];
for (const c of children) {
const inner = at(c, from, to);
if (inner) return inner;
}
return t;
}
function tree(
t: Term,
text: string,
): { label: string; range: Range; children?: ReturnType<typeof tree>[] } {
const range = rangeOf(text, t.span);
if (t.kind === "var") return { label: t.name, range };
if (t.kind === "lam") return { label: `λ${t.param}`, range, children: [tree(t.body, text)] };
return { label: "apply", range, children: [tree(t.fun, text), tree(t.arg, text)] };
}
function graph(t: Term) {
const nodes: { id: string; label: string; kind: string }[] = [];
const edges: { from: string; to: string; label?: string }[] = [];
const walk = (u: Term): string => {
const id = `n${nodes.length}`;
nodes.push({
id,
label: u.kind === "var" ? u.name : u.kind === "lam" ? `λ${u.param}` : "@",
kind: u.kind,
});
if (u.kind === "lam") edges.push({ from: id, to: walk(u.body) });
if (u.kind === "app") {
edges.push({ from: id, to: walk(u.fun), label: "fun" });
edges.push({ from: id, to: walk(u.arg), label: "arg" });
}
return id;
};
walk(t);
return { nodes, edges, layout: "tree" as const };
}
const code = (text: string): Item => ({
kind: "application/vnd.playground.code+json",
data: { language: "lambda-template", text },
});
const failure = (text: string, error: ParseError): { status: "error"; items: Item[] } => ({
status: "error",
items: [
{
kind: "application/vnd.playground.diagnostics+json",
data: [{ range: rangeOf(text, error.span), severity: 1, message: error.message }],
},
],
});
serve({
name: "lambda-template",
version: "1.0.0",
outputs: [
{
id: "run",
title: "Normal form",
triggers: ["run"],
kinds: [
"application/vnd.playground.code+json",
"text/plain",
"application/vnd.playground.diagnostics+json",
],
},
{
id: "steps",
title: "Steps",
triggers: ["demand"],
kinds: [
"application/vnd.playground.code+json",
"text/plain",
"application/vnd.playground.diagnostics+json",
],
},
{
id: "debruijn",
title: "De Bruijn",
triggers: ["change"],
kinds: [
"application/vnd.playground.code+json",
"application/vnd.playground.diagnostics+json",
],
},
{
id: "tree",
title: "Syntax tree",
triggers: ["demand"],
needs: "selection",
kinds: [
"application/vnd.playground.tree+json",
"text/plain",
"application/vnd.playground.diagnostics+json",
],
},
{
id: "graph",
title: "Graph",
triggers: ["demand"],
kinds: [
"application/vnd.playground.graph+json",
"text/plain",
"application/vnd.playground.diagnostics+json",
],
},
],
diagnose(document) {
const program = parsed(document.text);
if (program instanceof ParseError)
return [
{
range: rangeOf(document.text, program.span),
severity: 1,
message: program.message,
source: "lambda-template",
},
];
return unbound(program).map((u) => ({
range: rangeOf(document.text, u.span),
severity: 2,
message: `${u.name} is free: it is not bound or defined`,
source: "lambda-template",
}));
},
hover(document, position) {
const program = parsed(document.text);
if (program instanceof ParseError) return null;
const offset = lines(document.text).offset(position);
for (const t of [
...program.definitions.map((d) => d.term),
...(program.main ? [program.main] : []),
]) {
const sub = at(t, offset, offset);
if (sub) return `\`${show(sub)}\`\n\nde Bruijn: \`${deBruijn(sub)}\``;
}
return null;
},
completion(document) {
const program = parsed(document.text);
const names = program instanceof ParseError ? [] : program.definitions.map((d) => d.name);
return [
...names.map((label) => ({ label, kind: 6, detail: "definition" })),
{ label: "λ", kind: 14, detail: "abstraction" },
];
},
produce: {
run({ document }) {
const program = parsed(document.text);
if (program instanceof ParseError) return failure(document.text, program);
let t = expand(program);
if (!t)
return { status: "ok", items: [{ kind: "text/plain", data: "No term to evaluate.\n" }] };
for (let i = 0; i < LIMIT; i++) {
const next = step(t);
if (!next) return { status: "ok", items: [code(show(t))] };
t = next;
}
return {
status: "error",
items: [{ kind: "text/plain", data: `No normal form within ${LIMIT} steps.\n` }],
};
},
async steps({ document, emit, signal }) {
const program = parsed(document.text);
if (program instanceof ParseError) return failure(document.text, program);
let t = expand(program);
if (!t) return "ok";
emit([code(show(t))]);
for (let i = 0; i < SHOWN_STEPS && !signal.aborted; i++) {
const next = step(t);
if (!next) return "ok";
t = next;
emit([code(`→ ${show(t)}`)]);
await new Promise((r) => setTimeout(r, 0));
}
if (!step(t)) return "ok";
return {
status: "ok",
items: [{ kind: "text/plain", data: `… (${SHOWN_STEPS} steps shown)\n` }],
};
},
debruijn({ document }) {
const program = parsed(document.text);
if (program instanceof ParseError) return failure(document.text, program);
const t = expand(program);
return { status: "ok", items: t ? [code(deBruijn(t))] : [] };
},
tree({ document, range }) {
const program = parsed(document.text);
if (program instanceof ParseError) return failure(document.text, program);
const l = lines(document.text);
const from = range ? l.offset(range.start) : 0;
const to = range ? l.offset(range.end) : 0;
const terms = [
...program.definitions.map((d) => d.term),
...(program.main ? [program.main] : []),
];
const sub = terms.map((t) => at(t, from, to)).find((t) => t !== undefined) ?? program.main;
if (!sub) return { status: "ok", items: [{ kind: "text/plain", data: "No term here.\n" }] };
return {
status: "ok",
items: [{ kind: "application/vnd.playground.tree+json", data: tree(sub, document.text) }],
};
},
graph({ document }) {
const program = parsed(document.text);
if (program instanceof ParseError) return failure(document.text, program);
const t = expand(program);
if (!t) return { status: "ok", items: [{ kind: "text/plain", data: "No term to draw.\n" }] };
return {
status: "ok",
items: [{ kind: "application/vnd.playground.graph+json", data: graph(t) }],
};
},
},
});
Make your own
- Adding a language: the guide, from a runtime to a site.
- The templates to copy: TypeScript (the one above) and Rust, as WebAssembly.
- The conformance kit checks a package against the protocol.
- The package protocol, for implementers.