AIStoreHub Package Vault: Bend
Package Slug: bend
Archetype: tool
Upstream Repository: https://github.com/bendlang/bend
Workspace Files & Specifications (67 files)
- AGENTS.md (3282 bytes)
# AGENTS Bend is a dependently typed, affine language that checks in one linear bidirectional pass and runs massively parallel on CPU threads and GPUs. bend2/bend.ts is the language (parser, theory, checker) and is human-written: do not edit it. bend2/comp.ts is the one compiler: the C runtime (host and device from one source), the C emitter and the JS emitter; base.bend is the prelude; main.ts is the CLI. Every test is a Bend file that ends in the `#|` lines its run must print, and the gates run on the mini cluster. bend2/bend.ts the language: parser, theory, checker bend2/comp.ts the compiler and the runtimes (C, Metal, CUDA, JS) bend2/main.ts the CLI; imported, the .bend loader for bun and node bend2/safe.ts --verdict and -o <out>.bendtt: the elaborator from a checked book to BendTT text bend2/bendtt.lean BendTT: the kernel, its claims (no checked def has type Empty, live code halts) and their proofs; --verdict builds its CLI once, with Lean v4.34.0 bend2/base.bend the base library bend2/effs/ IO effect sources per backend; related effects may share bend2/pack/ package.json, tsconfig.json, bun.lock bend2/docs/ the papers' Typst sources, the film, gen_pins.ts (the record pins on this Mac), gen_charts.ts (the landing page's and the film's numbers), gen_gifs.ts (the images) bench/runtime/ one dir per bench: main.bend and its twins (C, TS, Lean) bench/checker/ one dir per bench: main.bend and its rivals bench/*/_pin_/ the pins, one file per hardware: apple_m4 the gate's, apple_m4_max the record tests/<ns>/ the tests by namespace, with their foreign .c/.js gates/test.ts every test, one shard per live mini, PASS: n / n gates/perf.ts the benches on 48 minis against the pins (--pin writes the medians of three runs) gates/repo.ts the allow list of files and the permanent ttok caps (bend.ts 48k, comp.ts 66k, main.ts 16k, bendtt.lean 64k, README 4k, GUIDE 8k); only Taelin changes them gates/ping.ts the installer, the compiled bend, its daily version check and a release, on a localhost hub gates/safe.ts bend2's verdict against BendTT's, per file, on the minis: `tests` or `hub` (a BendHub store, $SAFE_HUB) gates/_run.ts the four gates with --gate demos/ one dir per demo guide/ GUIDE.md paper/ BendTT.pdf, BendRT.pdf media/ the film and the charts .github/ ISSUE_TEMPLATE/bug.yml, the bug report form, and config.yml, which points questions at Discord ../bend-lang.com the site repo (bendlang/bend-lang.com), a sibling checkout: the sites, install.sh, the hub, release.ts (the executables per platform) and the droplet ops; gates/ping.ts and gen_charts.ts read it there (or at $SITE_REPO) - aistorehub.json (467 bytes)
{ "name": "Bend", "slug": "bend", "version": "1.0.0", "type": "tool", "description": "Bend 2: a fast language that blocks AI mistakes via proof. Install: curl -fsSL https://bend-lang.com/install.sh | sh", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/bendlang/bend", "tags": [ "trending", "typescript", "github", "open-source", "bendlang" ], "imported_at": "2026-11-21T23:56:29.493Z" } - bench/checker/_pin_/apple_m4_max.txt (559 bytes)
# Checker # 2026-09-09 f655a39d bun bend2/docs/gen_pins.ts checker; isabelle kept from 2026-09-02 0bf427f, not measured | bench | Isabelle | Agda | Lean | Rocq | Bend | |---------------|----------|----------|----------|----------|----------| | defs_12800 | >300s | >300s | 36.177s | 5.985s | 0.295s | | generics_3200 | >300s | >300s | 19.214s | 6.038s | 0.384s | | proofs_3200 | >300s | >300s | >300s | 9.526s | 0.834s | | trees_400 | 8.475s | 3.266s | 1.335s | 1.339s | 0.606s |
- bench/checker/_pin_/apple_m4.txt (249 bytes)
# 2026-09-09 26de367b bun gates/perf.ts --pin | bench | CHECKER | |---------------|----------| | compute_1600 | 0.541s | | defs_12800 | 0.302s | | generics_3200 | 0.353s | | proofs_3200 | 0.811s | | trees_400 | 0.579s |
- bench/runtime/_pin_/apple_m4_max.txt (1940 bytes)
# Runtime # 2026-09-17 d0db7b3e bun bend2/docs/gen_pins.ts runtime | bench | SEQ-CPU | PAR-CPU | PAR-GPU | C | TS | Lean | |--------------|-----------------|-----------------|-----------------|----------|----------|----------| | bfs | 3.918s 2.0M | 0.343s 2.7M | 0.207s 16.8M | 3.585s | 6.534s | 9.274s | | editdist | 2.559s 2.0M | 0.236s 3.1M | 0.144s 16.8M | 2.002s | 5.290s | 4.799s | | gameoflife | 7.803s 2.1M | 0.647s 2.7M | 0.063s 16.7M | 6.776s | 18.754s | 13.849s | | hashmap | 2.741s 2.4M | 0.238s 9.0M | 0.521s 16.8M | 0.622s | 0.892s | 1.526s | | kmeans | 2.069s 23.5M | 0.268s 24.1M | 0.191s 17.1M | 2.062s | 17.455s | 5.686s | | lexer | 2.144s 2.0M | 0.198s 3.0M | 1.075s 16.9M | 1.036s | 3.543s | 4.487s | | mandelbrot | 4.473s 2.3M | 0.395s 2.9M | 0.057s 16.9M | 3.750s | 3.837s | 4.575s | | merkle | 4.222s 130M | 0.422s 131M | 0.071s 17.5M | 3.423s | 7.227s | 5.986s | | nbody | 5.758s 2.2M | 0.516s 2.7M | 0.059s 16.8M | 5.126s | 5.332s | 5.387s | | queens | 5.406s 2.0M | 0.455s 2.5M | 0.933s 16.8M | 3.599s | 6.979s | 7.704s | | raytrace | 4.616s 2.1M | 0.396s 2.6M | 0.151s 17.0M | 3.646s | 23.039s | 10.825s | | symreg | 3.014s 2.1M | 0.266s 3.1M | 0.529s 17.1M | 2.208s | 5.924s | 2.457s | | terrain | 2.225s 2.1M | 0.197s 3.3M | 0.106s 16.9M | 2.198s | 5.746s | 8.039s | | tree-bitonic | 6.043s 146M | 0.799s 156M | 0.450s 17.0M | 5.719s | 33.910s | 38.123s | | tree-matmul | 2.064s 2.8M | 0.226s 14.8M | 0.231s 17.3M | 2.964s | 11.379s | 7.758s | | tree-radix | 4.083s 651M | 0.445s 617M | 0.314s 17.0M | 2.791s | 6.244s | 6.500s |
- bench/runtime/_pin_/apple_m4.txt (2244 bytes)
# 2026-10-08 the SEQ-CPU, PAR-CPU and PAR-GPU times are the medians of 5 gate runs (each cell timed by tm, the median of three runs under 2 s) at the commit each was pinned at: 35dbdb75; 386b7fc1 for bitonic, kmeans and nbody SEQ and PAR; d04cf05e for histogram. COMPILER and the spaces as 2026-09-11 b20509fd bun gates/perf.ts (the COMPILER column: medians of three runs, by hand) | bench | COMPILER | SEQ-CPU | PAR-CPU | PAR-GPU | OUTPUT | |--------------|----------|------------------|------------------|------------------|------------| | bfs | 0.578s | 3.501s 1.9M | 0.500s 2.6M | 0.894s 13.9M | 651176970 | | editdist | 0.562s | 1.916s 2.0M | 0.393s 3.0M | 0.476s 13.8M | 2229810577 | | gameoflife | 0.553s | 6.919s 2.0M | 1.151s 2.6M | 0.085s 13.9M | 2016151040 | | hashmap | 0.661s | 3.281s 2.3M | 0.509s 9.0M | 1.543s 14.0M | 1307803744 | | histogram | 1.033s | 1.466s 67.7M | 0.312s 74.8M | 1.477s 80.0M | 122845198 | | kmeans | 1.094s | 3.772s 23.5M | 0.826s 21.0M | 0.684s 15.8M | 1616398086 | | lexer | 0.646s | 2.292s 1.9M | 0.427s 2.9M | 3.923s 14.1M | 2401049475 | | mandelbrot | 0.637s | 4.444s 2.2M | 0.677s 2.8M | 0.067s 13.6M | 3101455856 | | merkle | 0.597s | 4.166s 130M | 0.771s 131M | 0.080s 13.9M | 3104235417 | | nbody | 0.671s | 5.894s 2.1M | 0.842s 2.6M | 0.061s 14.2M | 3516450380 | | queens | 0.602s | 4.745s 2.0M | 0.770s 2.5M | 2.701s 13.9M | 2063750025 | | raytrace | 0.652s | 4.346s 2.0M | 0.730s 2.6M | 0.391s 14.0M | 1924309504 | | symreg | 0.686s | 2.744s 2.0M | 0.466s 3.0M | 0.807s 14.3M | 2383953211 | | terrain | 0.622s | 2.139s 2.0M | 0.360s 3.3M | 0.313s 13.9M | 2572468224 | | tree-bitonic | 0.666s | 5.490s 146M | 1.185s 159M | 1.966s 14.3M | 3787129428 | | tree-matmul | 1.473s | 1.861s 2.8M | 0.371s 15.3M | 1.013s 16.8M | 3797651056 | | tree-radix | 0.668s | 3.780s 651M | 0.738s 615M | 1.025s 14.5M | 1998173798 |
- bench/runtime/bfs/main.ts (2914 bytes)
// TypeScript twin of main.bend: breadth-first search over 2^DEPTH // independent 32x32 grid mazes, single-threaded, 1-to-1 with the Bend // program: same seed and wall hash, a Uint32Array grid (1 open, 0 // wall), a Uint32Array queue with head and tail, a Uint32Array distance // map seeded unseen, the textbook pop loop with four bounds-checked // neighbour looks, and the same position-weighted fold sealed by the // reached count (imul + >>>0 for the wrapping-u32 numerics); leaf // checksums sum up the batch recursion. const DEPTH = 19; const CELLS = 1024; const UNSEEN = 0xffffffff; class Bfs { g = new Uint32Array(CELLS); q = new Uint32Array(CELLS); d = new Uint32Array(CELLS); head = 0; tail = 0; } function word_prng(x: number): number { const b = (x ^ (x << 13)) >>> 0; const d = (b ^ (b >>> 17)) >>> 0; return (d ^ (d << 5)) >>> 0; } // 1 when cell c of the maze seeded s is open: the start always, any // other cell when its hash mod 100 is 30 or more (30% walls) function cell_open(s: number, c: number): number { const h = word_prng((s ^ Math.imul(c + 1, 340573321)) >>> 0); return c === 0 || h % 100 >= 30 ? 1 : 0; } // one neighbour n at distance v: skip it out of bounds, a wall or // seen; else stamp its distance and push it function bfs_look(b: Bfs, n: number, v: number, inb: boolean): void { if (inb && b.g[n] !== 0 && b.d[n] === UNSEEN) { b.d[n] = v; b.q[b.tail] = n; b.tail += 1; } } // one pop: the head cell and its distance, then its four neighbours function bfs_pop(b: Bfs): void { const c = b.q[b.head]; const v = (b.d[c] + 1) >>> 0; const x = c & 31; const y = c >>> 5; b.head += 1; bfs_look(b, (c - 1) >>> 0, v, x > 0); bfs_look(b, c + 1, v, x < 31); bfs_look(b, (c - 32) >>> 0, v, y > 0); bfs_look(b, c + 32, v, y < 31); } // the leaf checksum: a reached cell mixes its distance position- // weighted and counts one; the count seals the mix function bfs_fold(b: Bfs): number { let acc = 0; let cnt = 0; for (let c = 0; c < CELLS; c++) { const v = b.d[c]; const hit = v !== UNSEEN ? 1 : 0; acc = (Math.imul(acc, 2654435761) ^ (hit ? Math.imul(v, c + 1) : 0)) >>> 0; cnt = (cnt + hit) >>> 0; } return (acc ^ Math.imul(cnt, 2246822519)) >>> 0; } // one maze: fill the grid, seed the search with cell 0 at distance 0, // search, fold function maze_run(m: number): number { const b = new Bfs(); const s = Math.imul(m + 1, 2654435761) >>> 0; for (let c = 0; c < CELLS; c++) { b.g[c] = cell_open(s, c); b.d[c] = UNSEEN; } b.d[0] = 0; b.head = 0; b.tail = 1; while (b.head < b.tail) { bfs_pop(b); } return bfs_fold(b); } function batch_run(k: number, i: number): number { if (k === 0) { return maze_run(i); } const a = batch_run(k - 1, i); const b = batch_run(k - 1, (i + (1 << (k - 1))) >>> 0); return (a + b) >>> 0; } console.log(batch_run(DEPTH, 0)); - bench/runtime/editdist/main.ts (2051 bytes)
// Native TypeScript twin of main.bend: Levenshtein edit distance by // dynamic programming, single-threaded, 1-to-1 with the Bend program: // the same xorshift symbol streams (sequences are Uint8Arrays), the // same two rolling Uint32Array rows swapping roles after every row, // the same min chain and cost test per cell, and the same checksum // fold over the pair index space (imul + >>>0 for wrapping u32). const DEPTH = 15; const N = 256; function word_prng(x: number): number { const b = (x ^ (x << 13)) >>> 0; const d = (b ^ (b >>> 17)) >>> 0; return (d ^ (d << 5)) >>> 0; } // draw one sequence: step the stream, keep its low two bits function seq_gen(s: number, x: Uint8Array): void { for (let k = 0; k < N; k++) { s = word_prng(s); x[k] = s & 3; } } // the DP: prev[j] = j at the start; row i reads a[i] once, writes // cur[0] = i + 1, fills cur[1..N], then the rows swap roles function edit_dist(a: Uint8Array, b: Uint8Array): number { let prev = new Uint32Array(N + 1); let cur = new Uint32Array(N + 1); for (let k = 0; k <= N; k++) { prev[k] = k; } for (let i = 0; i < N; i++) { const ai = a[i]; cur[0] = i + 1; for (let j = 0; j < N; j++) { const cost = ai !== b[j] ? 1 : 0; cur[j + 1] = Math.min(Math.min(prev[j + 1] + 1, cur[j] + 1), prev[j] + cost); } const t = prev; prev = cur; cur = t; } return prev[N]; } // one pair: seed from the hashed pair index, draw a and b, run the // DP, mix the distance with the index function pair_run(p: number): number { const a = new Uint8Array(N); const b = new Uint8Array(N); const s = Math.imul(p + 1, 2654435761) >>> 0; seq_gen(s, a); seq_gen(Math.imul(s, 340573321) >>> 0, b); return (Math.imul(edit_dist(a, b), 2654435761) ^ (p + 1)) >>> 0; } function batch_run(d: number, p: number): number { if (d === 0) { return pair_run(p); } const x = batch_run(d - 1, p); const y = batch_run(d - 1, (p + (1 << (d - 1))) >>> 0); return (x + y) >>> 0; } console.log(batch_run(DEPTH, 0)); - bench/runtime/gameoflife/main.ts (3744 bytes)
// Native TypeScript twin of main.bend: Conway soup census. Same // bit-packed 4x4-torus step, SWAR popcount, two-probe classification, // 64-soup chunks and census merge, wrapping-u32 numerics (imul + >>>0). const word_wrap = (value: number): number => value >>> 0; type Census = { pop: number; still: number; osc: number; mix: number }; function cell_get(board: number, r: number, c: number): number { return (board >>> (((r & 3) * 4 + (c & 3)) & 31)) & 1; } function neighbor_count(board: number, r: number, c: number): number { return ( cell_get(board, r - 1, c - 1) + cell_get(board, r - 1, c) + cell_get(board, r - 1, c + 1) + cell_get(board, r, c - 1) + cell_get(board, r, c + 1) + cell_get(board, r + 1, c - 1) + cell_get(board, r + 1, c) + cell_get(board, r + 1, c + 1) ); } function to_bool(k: number): number { return k === 0 ? 0 : 1; } function next_dead(n: number): number { return to_bool(n === 3 ? 1 : 0); } function next_alive(n: number): number { return to_bool((n === 2 ? 1 : 0) | (n === 3 ? 1 : 0)); } function next_cell(a: number, n: number): number { return a === 0 ? next_dead(n) : next_alive(n); } function step_cell(board: number, pos: number): number { const r = pos >>> 2; const c = pos & 3; const alive = cell_get(board, r, c); const neighbors = neighbor_count(board, r, c); return next_cell(alive, neighbors) << (pos & 31); } function board_step(b: number): number { let next = 0; for (let pos = 0; pos < 16; pos++) { next |= step_cell(b, pos); } return next >>> 0; } function board_run(n: number, board: number): number { while (n !== 0) { board = board_step(board); n--; } return board; } // 16-bit SWAR population count function board_popcount(b: number): number { const a = word_wrap(b - ((b >>> 1) & 21845)); const c = (a & 13107) + ((a >>> 2) & 13107); const d = (c + (c >>> 4)) & 3855; return ((d * 257) >>> 8) & 31; } // classify the settled board by two probe steps: 0 still, 1 osc, 2 chaos function board_classify(b: number): number { const n1 = board_step(b); if (n1 === b) { return 0; } const n2 = board_step(n1); return n2 === b ? 1 : 2; } // one soup: hash the soup index into a 16-bit board, run GENS steps function soup_sim(ix: number, g: number): number { return board_run(g, word_wrap(Math.imul(ix, 2654435761)) & 65535); } // leaf chunk: 64 soups folded into scalar accumulators function chunk_run(j: number, i: number, g: number): Census { let pa = 0; let sa = 0; let oa = 0; let mx = 0; while (j !== 0) { const bd = soup_sim(word_wrap(i + j - 1), g); const p = board_popcount(bd); const c = board_classify(bd); mx = word_wrap(Math.imul(mx, 2654435761) ^ bd); pa = word_wrap(pa + p); sa = word_wrap(sa + (c === 0 ? 1 : 0)); oa = word_wrap(oa + (c === 1 ? 1 : 0)); j--; } return { pop: pa, still: sa, osc: oa, mix: mx }; } function census_zip(a: Census, b: Census): Census { return { pop: word_wrap(a.pop + b.pop), still: word_wrap(a.still + b.still), osc: word_wrap(a.osc + b.osc), mix: word_wrap(Math.imul(a.mix, 2654435761) + b.mix), }; } function batch_run(d: number, i: number, g: number): Census { if (d === 0) { return chunk_run(64, i, g); } const a = batch_run(d - 1, i, g); const b = batch_run(d - 1, word_wrap(i + (64 << (d - 1))), g); return census_zip(a, b); } // final checksum: mix the census fields function census_fin(c: Census): number { return word_wrap( Math.imul( word_wrap( Math.imul(word_wrap(Math.imul(c.pop, 2654435761) + c.still), 2654435761) + c.osc, ), 2654435761, ) + c.mix, ); } console.log(census_fin(batch_run(18, 0, 32))); - bench/runtime/hashmap/main.ts (3081 bytes)
// TypeScript twin of main.bend: a hash table with separate chaining // over 2^S independent tables. Same xorshift key of the seed and draw // index masked to 20 bits, same low-12-bit bucket, same walk (it // stops at the found key; Bend's stops one node later), same head // insert, same hit count, same position-weighted fold over the chain // lengths, same sum over the table tree, wrapping-u32 numerics (imul // + >>>0). A table is an array of 4096 bucket heads, each a linked // chain of Node objects (monomorphic shape); the GC plays the role // of the linear frees. const TABLES = 11; const KEYS = 16384; const word_wrap = (value: number): number => value >>> 0; class Node { k: number; next: Node | null; constructor(k: number, next: Node | null) { this.k = k; this.next = next; } } function word_prng(x: number): number { const b = word_wrap(x ^ (x << 13)); const d = word_wrap(b ^ (b >>> 17)); return word_wrap(d ^ (d << 5)); } // a key: the hash of a seed and a draw index, masked to 20 bits function draw_key(s: number, j: number): number { const mj = Math.imul(j + 1, 2654435761); const ms = Math.imul(s, 340573321); return word_prng(word_wrap(mj ^ ms)) & 1048575; } // the chain walk: 1 when the key is in the chain, stopping at it function chain_has(c: Node | null, k: number): number { for (let n = c; n !== null; n = n.next) { if (n.k === k) { return 1; } } return 0; } // a chain's length function chain_len(c: Node | null): number { let l = 0; for (let n = c; n !== null; n = n.next) { l++; } return l; } // one insert: a present key leaves the bucket untouched, an absent // one is consed onto the chain function table_ins(t: (Node | null)[], k: number): void { const b = k & 4095; if (!chain_has(t[b], k)) { t[b] = new Node(k, t[b]); } } // one table: D inserts from the table seed, D lookups from the second // seed, then the bucket sweep: lengths summed (the distinct count) and // mixed position-weighted, sealed with the hit count function table_run(ti: number, d: number): number { const t: (Node | null)[] = new Array(4096).fill(null); const s = Math.imul(ti + 1, 2654435761) >>> 0; for (let j = 0; j < d; j++) { table_ins(t, draw_key(s, j)); } const s2 = word_prng(s); let hits = 0; for (let j = 0; j < d; j++) { const k = draw_key(s2, j); hits += chain_has(t[k & 4095], k); } let cnt = 0; let acc = 0; for (let i = 0; i < 4096; i++) { const l = chain_len(t[i]); cnt = word_wrap(cnt + l); acc = word_wrap(Math.imul(acc, 2654435761) ^ Math.imul(l, i + 3)); } const sealed = word_wrap(acc ^ Math.imul(hits, 2654435761)); return word_wrap(sealed + Math.imul(cnt, 340573321)); } // batch tree over the table index space: table checksums sum up function batch_run(p: number, t: number, d: number): number { if (p === 0) { return table_run(t, d); } const a = batch_run(p - 1, t, d); const b = batch_run(p - 1, word_wrap(t + (1 << (p - 1))), d); return word_wrap(a + b); } console.log(batch_run(TABLES, 0, KEYS)); - bench/runtime/histogram/main.ts (2479 bytes)
// Native TypeScript twin of main.bend: a histogram of R fresh batches of // 2^D keys into K = 256 buckets, single-threaded, 1-to-1 with the Bend // program: per round, the same key stream (seed 7 + r) filled block by // block, the same two passes over the same 2^B x 256 Uint32Array table // (pass 1 zeroes and counts each block's row; pass 2 sums the columns, // in two steps from 2^12 rows up), and the same fold of the round's // counts (imul + >>>0 for wrapping u32). const D = 24; const B = 11; const R = 128; const K = 256; const KB = 8; function word_prng(x: number): number { const a = (x ^ (x << 13)) >>> 0; const b = (a ^ (a >>> 17)) >>> 0; return (b ^ (b << 5)) >>> 0; } function key(s: number, j: number): number { return word_prng(word_prng((Math.imul(j + 1, 2654435761) + s) >>> 0)) % K; } // pass 2: the columns, over the 2^d rows; from 2^12 rows up, each // column's sum over a group of 2^m rows into the group's last row, then // over the 2^r groups' last rows function cols(d: number, t: Uint32Array, cs: Uint32Array): void { const r = d < 12 ? d : d >>> 1; const m = d < 12 ? 0 : d - r; if (d >= 12) { for (let g = 0; g < 1 << r; g++) { const top = g << (m + KB); const last = top + (((1 << m) - 1) << KB); for (let c = 0; c < K; c++) { let s = 0; for (let i = 0; i < 1 << m; i++) { s = (s + t[top + (i << KB) + c]) >>> 0; } t[last + c] = s; } } } const o = ((1 << m) - 1) << KB; for (let c = 0; c < K; c++) { let s = 0; for (let g = 0; g < 1 << r; g++) { s = (s + t[o + (g << (m + KB)) + c]) >>> 0; } cs[c] = s; } } // one count: pass 1 per block (its row zeroed, then its 2^e keys counted // into it), then pass 2 function count(d: number, e: number, ks: Uint32Array, t: Uint32Array, cs: Uint32Array): void { for (let i = 0; i < 1 << d; i++) { const row = i << KB; for (let c = 0; c < K; c++) { t[row + c] = 0; } for (let j = i << e; j < (i + 1) << e; j++) { t[row + Math.min(ks[j], K - 1)]++; } } cols(d, t, cs); } const d = Math.min(B, D); const ks = new Uint32Array(1 << D); const t = new Uint32Array(1 << (d + KB)); const cs = new Uint32Array(K); let h = 0; for (let n = 0; n < R; n++) { for (let j = 0; j < 1 << D; j++) { ks[j] = key(7 + n, j); } count(d, D - d, ks, t, cs); for (let c = 0; c < K; c++) { h = (Math.imul(h, 2654435761) ^ cs[c]) >>> 0; } } console.log(h); - bench/runtime/kmeans/main.ts (5095 bytes)
// Native TS translation of main.bend: k-means with random // restarts; stats trees live in a typed-array arena (u32 indices, // same representation as the C twin). const STATS_LEAF = 0, STATS_NODE = 1; let arena_tag = new Uint8Array(1 << 16), arena_a = new Uint32Array(1 << 16), arena_b = new Uint32Array(1 << 16), arena_c = new Uint32Array(1 << 16), arena_len = 0; function stats_push(tag: number, a: number, b: number, c: number): number { if (arena_len === arena_tag.length) { const n = arena_tag.length * 2; const t2 = new Uint8Array(n), a2 = new Uint32Array(n), b2 = new Uint32Array(n), c2 = new Uint32Array(n); t2.set(arena_tag); a2.set(arena_a); b2.set(arena_b); c2.set(arena_c); arena_tag = t2; arena_a = a2; arena_b = b2; arena_c = c2; } const i = arena_len++; arena_tag[i] = tag; arena_a[i] = a; arena_b[i] = b; arena_c[i] = c; return i; } function word_prng(x: number): number { x = (x ^ (x << 13)) >>> 0; x = (x ^ (x >>> 17)) >>> 0; return (x ^ (x << 5)) >>> 0; } function value_select(t: number, x: number, y: number): number { return t ? y : x; } function value_min(a: number, b: number): number { return value_select(a < b ? 1 : 0, b, a); } function point_distance(x: number, y: number, c: number, k: number): number { const cx = c & 65535, cy = c >>> 16, dx = value_select(x < cx ? 1 : 0, (x - cx) >>> 0, (cx - x) >>> 0), dy = value_select(y < cy ? 1 : 0, (y - cy) >>> 0, (cy - y) >>> 0); return ((((dx * dx + dy * dy) << 3) | k) >>> 0); } function stats_zip(x: number, y: number): number { const tx = arena_tag[x], ty = arena_tag[y]; if (tx === STATS_LEAF && ty === STATS_LEAF) return stats_push( STATS_LEAF, (arena_a[x] + arena_a[y]) >>> 0, (arena_b[x] + arena_b[y]) >>> 0, (arena_c[x] + arena_c[y]) >>> 0, ); if (tx === STATS_LEAF) return x; if (ty === STATS_LEAF) return x; const l = stats_zip(arena_a[x], arena_a[y]); const r = stats_zip(arena_b[x], arena_b[y]); return stats_push(STATS_NODE, l, r, 0); } function stats_chunk(i: number, c: Uint32Array): number { const sx = new Uint32Array(8), sy = new Uint32Array(8), nn = new Uint32Array(8); for (let j = 64; j; j--) { const h = word_prng(Math.imul((i + j) >>> 0, 2654435761) >>> 0), x = h & 1023, y = (h >>> 16) & 1023; const b = value_min( value_min( value_min(point_distance(x, y, c[0], 0), point_distance(x, y, c[1], 1)), value_min(point_distance(x, y, c[2], 2), point_distance(x, y, c[3], 3)), ), value_min( value_min(point_distance(x, y, c[4], 4), point_distance(x, y, c[5], 5)), value_min(point_distance(x, y, c[6], 6), point_distance(x, y, c[7], 7)), ), ) & 7; sx[b] += x; sy[b] += y; nn[b]++; } const q: number[] = []; for (let k = 0; k < 8; k++) q.push(stats_push(STATS_LEAF, sx[k], sy[k], nn[k])); return stats_push( STATS_NODE, stats_push(STATS_NODE, stats_push(STATS_NODE, q[0], q[1], 0), stats_push(STATS_NODE, q[2], q[3], 0), 0), stats_push(STATS_NODE, stats_push(STATS_NODE, q[4], q[5], 0), stats_push(STATS_NODE, q[6], q[7], 0), 0), 0, ); } function stats_fold(d: number, i: number, c: Uint32Array): number { if (d === 0) return stats_chunk(i, c); const x = stats_fold(d - 1, i, c); const y = stats_fold(d - 1, (i + (64 << (d - 1))) >>> 0, c); return stats_zip(x, y); } function stats_centroid(s: number, old: number): number { if (arena_tag[s] === STATS_NODE) return old; const n = arena_c[s], m = n ? n : 1, next = (Math.floor(arena_a[s] / m) | (Math.floor(arena_b[s] / m) << 16)) >>> 0; return n ? next : old; } function stats_split(s: number, out: number[], at: number): void { if (arena_tag[s] === STATS_NODE) { out[at] = arena_a[s]; out[at + 1] = arena_b[s]; } else { out[at] = s; out[at + 1] = stats_push(STATS_LEAF, 0, 0, 0); } } function centroids_step(d: number, c: Uint32Array): void { arena_len = 0; const root = stats_fold(d - 6, 0, c), p = [0, 0], q = [0, 0, 0, 0], z = [0, 0, 0, 0, 0, 0, 0, 0]; stats_split(root, p, 0); stats_split(p[0], q, 0); stats_split(p[1], q, 2); for (let i = 0; i < 4; i++) stats_split(q[i], z, 2 * i); for (let i = 0; i < 8; i++) c[i] = stats_centroid(z[i], c[i]); } function centroid_initial(k: number): number { const h = word_prng((12345 + k) >>> 0); return ((h & 1023) | (((h >>> 16) & 1023) << 16)) >>> 0; } function restart_run(r: number, d: number): number { const c = new Uint32Array(8); for (let k = 0; k < 8; k++) c[k] = centroid_initial(r * 8 + k + 1); for (let n = 0; n < 20; n++) centroids_step(d, c); let h = c[0]; for (let k = 1; k < 8; k++) h = (Math.imul(h, 2654435761) + c[k]) >>> 0; return h; } function restart_batch(b: number, r: number, d: number): number { return b === 0 ? restart_run(r, d) : (restart_batch(b - 1, r, d) + restart_batch(b - 1, r + (1 << (b - 1)), d)) >>> 0; } console.log(restart_batch(6, 0, 19)); - bench/runtime/lexer/main.ts (2367 bytes)
// TypeScript twin of main.bend: same template generator into a JS // string, same tokenizer over its char codes (nested loops, one per // token class), same checksum, single-threaded. Wrapping u32 // arithmetic rides Math.imul and >>> 0. const DEPTH = 23; const TPL = "i = ( n o i ) o ( n o i ) o ( n o i ) ;"; function prng(x: number): number { const b = (x ^ (x << 13)) >>> 0; const d = (b ^ (b >>> 17)) >>> 0; return (d ^ (d << 5)) >>> 0; } function seed(i: number): number { return prng(Math.imul(i + 1, 2654435761) >>> 0); } function salt(s: number, k: number): number { return prng((s ^ Math.imul(k, 2654435761)) >>> 0); } // one line of source from the template function gen(s: number): string { let line = ""; for (let k = 0; k < TPL.length; k++) { let t = salt(s, k); const c = TPL[k]; if (c === "i") { for (let j = 1 + (t & 7); j; j--) { t = prng(t); line += String.fromCharCode(97 + (t % 26)); } } else if (c === "n") { for (let j = 1 + (t % 6); j; j--) { t = prng(t); line += String.fromCharCode(48 + (t % 10)); } } else if (c === "o") { line += "+-*/"[t & 3]; } else { line += c; } } return line; } function mix(acc: number, kind: number, x: number): number { const tok = (Math.imul(kind, 40503) + x) >>> 0; return (Math.imul(acc, 2654435761) ^ tok) >>> 0; } function is_letter(c: number): boolean { return c >= 97 && c <= 122; } function is_digit(c: number): boolean { return c >= 48 && c <= 57; } // the tokenizer over one line's char codes function lex(p: string): number { let acc = 0; let i = 0; const n = p.length; while (i < n) { const c = p.charCodeAt(i); if (is_letter(c)) { let h = 2166136261; while (i < n && is_letter(p.charCodeAt(i))) { h = Math.imul(h ^ p.charCodeAt(i), 16777619) >>> 0; i++; } acc = mix(acc, 1, h); } else if (is_digit(c)) { let v = 0; while (i < n && is_digit(p.charCodeAt(i))) { v = (Math.imul(v, 10) + (p.charCodeAt(i) - 48)) >>> 0; i++; } acc = mix(acc, 2, v); } else if (c === 32) { i++; } else { acc = mix(acc, 3, c); i++; } } return acc; } let sum = 0; for (let i = 0; i < 2 ** DEPTH; i++) { sum = (sum + lex(gen(seed(i)))) >>> 0; } console.log(sum); - bench/runtime/mandelbrot/main.ts (2415 bytes)
// Native TS translation of main.bend: histogram-equalized // escape-time render, 4096x4096, signed 8.8 fixed point, ITERS // branchless iterations per pixel (z freezes at escape). const ITERS = 51, WIDTH = 4096; const word_wrap = (x: number): number => x >>> 0; function value_select(t: number, x: number, y: number): number { return t ? y : x; } // arithmetic shift right by 8 over two's-complement u32 function word_asr8(v: number): number { return word_wrap((v >>> 8) | value_select(v >>> 31, 0, 4278190080)); } // ITERS branchless escape-time iterations: z steps while esc == 0 and // freezes after, it counts the pre-escape iterations function pixel_iterate(n: number, cr: number, ci: number): number { let zr = 0, zi = 0, esc = 0, it = 0; for (; n; n--) { const r2 = word_asr8(Math.imul(zr, zr) >>> 0); const i2 = word_asr8(Math.imul(zi, zi) >>> 0); const e2 = esc | (word_wrap(r2 + i2) > 1024 ? 1 : 0); const nzr = word_wrap(word_wrap(r2 - i2) + cr); const nzi = word_wrap(word_asr8(Math.imul(2, Math.imul(zr, zi)) >>> 0) + ci); zr = value_select(e2, nzr, zr); zi = value_select(e2, nzi, zi); esc = e2; it = it + (e2 === 0 ? 1 : 0); } return it; } // one pixel: viewport [-2, 1) x [-1.5, 1.5) over the WIDTH^2 grid function pixel_escape(id: number): number { const cr = word_wrap(Math.floor(((id & (WIDTH - 1)) * 768) / WIDTH) - 512); const ci = word_wrap(Math.floor((Math.floor(id / WIDTH) * 768) / WIDTH) - 384); return pixel_iterate(ITERS, cr, ci); } // escape time -> one of 8 buckets, knob-stable function pixel_bucket(it: number): number { const bq = Math.floor((it * 8) / ITERS); return value_select(bq > 7 ? 1 : 0, bq, 7); } const total = WIDTH * WIDTH; const h = new Uint32Array(8); for (let i = 0; i < total; i++) h[pixel_bucket(pixel_escape(i))]++; const lut = new Uint32Array(8); let c = 0; for (let k = 0; k < 8; k++) { c = word_wrap(c + h[k]); lut[k] = c; } const cn = lut[7]; for (let k = 0; k < 8; k++) lut[k] = Math.floor((lut[k] * 255) / cn); let mix = lut[0]; for (let k = 1; k < 8; k++) mix = word_wrap(Math.imul(mix, 2654435761) + lut[k]); let r = 0; for (let i = 0; i < total; i++) { const it = pixel_escape(i); const col = lut[pixel_bucket(it)]; r = word_wrap(r + word_wrap(Math.imul(col, word_wrap(Math.imul(i, 2654435761) + 1)) + it)); } console.log(word_wrap(Math.imul(mix, 2654435761) + r)); - bench/runtime/merkle/main.ts (4011 bytes)
// TypeScript twin of main.bend: same Speck32/64 leaf stream, // Merkle tree build, audit re-fold, scalar-prover proof extraction and // proof verification, single-threaded. class MtLeaf { h: number; constructor(h: number) { this.h = h; } } class MtNode { h: number; l: Mt; r: Mt; constructor(h: number, l: Mt, r: Mt) { this.h = h; this.l = l; this.r = r; } } type Mt = MtLeaf | MtNode; class PathNil {} class PathCons { side: number; sib: number; rest: Path; constructor(side: number, sib: number, rest: Path) { this.side = side; this.sib = sib; this.rest = rest; } } type Path = PathNil | PathCons; const SIZE = 22; const BLOCKS = 30; const PROBE = 1337; const ROUND_KEYS = new Uint16Array([ 256, 5394, 24957, 5208, 26905, 30690, 3209, 52443, 61418, 20019, 30452, 22902, 61067, 56068, 17943, 62334, 34740, 36554, 60827, 14930, 33321, 60772, ]); function round_key(index: number): number { return ROUND_KEYS[index < 21 ? index : 21]; } // 22 Speck rounds over the 16-bit halves x, y function speck_run(rounds: number, index: number, x: number, y: number) { while (rounds !== 0) { const nextX = (((((x >>> 7) | (x << 9)) & 65535) + y) & 65535) ^ round_key(index); y = ((((y << 2) | (y >>> 14)) & 65535) ^ nextX) & 65535; x = nextX & 65535; index++; rounds--; } return (x | (y << 16)) >>> 0; } // one leaf: encrypt `count` counter blocks, chain the ciphertexts function block_chain(count: number, block: number, acc: number): number { while (count !== 0) { const ciphertext = speck_run(22, 0, block & 65535, (block >>> 16) & 65535); acc = (Math.imul(acc, 2654435761) + ciphertext) >>> 0; block = (block + 1) >>> 0; count--; } return acc; } function leaf_hash(b: number): number { return block_chain(BLOCKS, Math.imul(b, BLOCKS) >>> 0, (b + 1) >>> 0); } // Merkle join: ARX mix of the two child hashes function hash_join(left: number, right: number): number { const h = (Math.imul(left, 2654435761) ^ right) >>> 0; const h2 = (Math.imul((h + 2246822519) >>> 0, 2246822519) ^ (h >>> 13)) >>> 0; return (h2 ^ (h2 >>> 16)) >>> 0; } // the scalar prover: recompute a subtree hash without materializing it function hash_tree(depth: number, block: number): number { if (depth === 0) return leaf_hash(block); const left = hash_tree(depth - 1, block); const right = hash_tree(depth - 1, (block + (1 << (depth - 1))) >>> 0); return hash_join(left, right); } // join two subtrees into a hashed node (peek the child hashes) function mt_join(l: Mt, r: Mt): Mt { return new MtNode(hash_join(l.h, r.h), l, r); } // build the Merkle tree over blocks b .. b + 2^d - 1 function mt_build(d: number, b: number): Mt { if (d === 0) return new MtLeaf(leaf_hash(b)); const l = mt_build(d - 1, b); const r = mt_build(d - 1, (b + (1 << (d - 1))) >>> 0); return mt_join(l, r); } // audit: re-fold the tree; any stored-hash mismatch perturbs the result function mt_audit(t: Mt): number { if (t instanceof MtLeaf) return t.h; const x = mt_audit(t.l); const y = mt_audit(t.r); const m = hash_join(x, y); return (m + ((m ^ t.h) >>> 0)) >>> 0; } // Merkle proof for leaf k: per level, the side bit and the sibling hash function path_gen(d: number, k: number, b: number): Path { if (d === 0) return new PathNil(); const bit = (k >>> (d - 1)) & 1; const half = 1 << (d - 1); const sib = hash_tree(d - 1, bit === 0 ? (b + half) >>> 0 : b); const rest = path_gen(d - 1, k, bit === 0 ? b : (b + half) >>> 0); return new PathCons(bit, sib, rest); } // fold the proof back up from the leaf hash to a root hash function path_verify(p: Path, lh: number): number { if (p instanceof PathNil) return lh; const hh = path_verify(p.rest, lh); return p.side === 0 ? hash_join(hh, p.sib) : hash_join(p.sib, hh); } const t = mt_build(SIZE, 0); const root = mt_audit(t); const prf = path_gen(SIZE, PROBE, 0); console.log(hash_join(root, path_verify(prf, leaf_hash(PROBE)))); - bench/runtime/nbody/main.ts (5363 bytes)
// Native TS translation of main.bend: chaotic three-body ensemble, // f32 (Math.fround per op), Plummer-softened, symplectic Euler. const SY = 17, ST = 300; const f = Math.fround; function word_prng(x: number): number { x = (x ^ (x << 13)) >>> 0; x = (x ^ (x >>> 17)) >>> 0; return (x ^ (x << 5)) >>> 0; } // f32_to_u32: truncate toward zero; NaN, negative, or >= 2^32 -> 0 function float_word(v: number): number { if (Number.isNaN(v) || v < 1 || v >= 4294967296) return 0; return Math.floor(v) >>> 0; } function seed_hash(sd: number, k: number): number { return word_prng(Math.imul((sd * 12 + k) >>> 0, 2654435761) >>> 0); } function seed_unit(sd: number, k: number): number { return f(f((seed_hash(sd, k) & 65535) / 32768) - 1); } function seed_mass(sd: number, k: number): number { return f(f((seed_hash(sd, k) & 65535) / 65536) + 0.5); } // one random system: three seeded bodies, ST steps, digest [cs, eb] function system_run(sd: number, st: number): [number, number] { let x0 = seed_unit(sd, 1), y0 = seed_unit(sd, 2), z0 = seed_unit(sd, 3); const m0 = seed_mass(sd, 4); let x1 = seed_unit(sd, 5), y1 = seed_unit(sd, 6), z1 = seed_unit(sd, 7); const m1 = seed_mass(sd, 8); let x2 = seed_unit(sd, 9), y2 = seed_unit(sd, 10), z2 = seed_unit(sd, 11); const m2 = seed_mass(sd, 12); let vx0 = f(y0 * f(0.1)), vy0 = f(0 - f(x0 * f(0.1))), vz0 = 0; let vx1 = f(y1 * f(0.1)), vy1 = f(0 - f(x1 * f(0.1))), vz1 = 0; let vx2 = f(y2 * f(0.1)), vy2 = f(0 - f(x2 * f(0.1))), vz2 = 0; const dt = f(0.001), eps = f(0.05); for (let s = st; s; s--) { const ax = f(x1 - x0), ay = f(y1 - y0), az = f(z1 - z0); const da = f(f(f(ax * ax) + f(f(ay * ay) + f(az * az))) + eps); const ia = f(1 / f(Math.sqrt(da))); const i3a = f(f(ia * ia) * ia); const qax = f(ax * i3a), qay = f(ay * i3a), qaz = f(az * i3a); const bx = f(x2 - x0), by = f(y2 - y0), bz = f(z2 - z0); const db = f(f(f(bx * bx) + f(f(by * by) + f(bz * bz))) + eps); const ib = f(1 / f(Math.sqrt(db))); const i3b = f(f(ib * ib) * ib); const qbx = f(bx * i3b), qby = f(by * i3b), qbz = f(bz * i3b); const cx = f(x2 - x1), cy = f(y2 - y1), cz = f(z2 - z1); const dc = f(f(f(cx * cx) + f(f(cy * cy) + f(cz * cz))) + eps); const ic = f(1 / f(Math.sqrt(dc))); const i3c = f(f(ic * ic) * ic); const qcx = f(cx * i3c), qcy = f(cy * i3c), qcz = f(cz * i3c); vx0 = f(vx0 + f(f(f(qax * m1) + f(qbx * m2)) * dt)); vy0 = f(vy0 + f(f(f(qay * m1) + f(qby * m2)) * dt)); vz0 = f(vz0 + f(f(f(qaz * m1) + f(qbz * m2)) * dt)); vx1 = f(vx1 + f(f(f(qcx * m2) - f(qax * m0)) * dt)); vy1 = f(vy1 + f(f(f(qcy * m2) - f(qay * m0)) * dt)); vz1 = f(vz1 + f(f(f(qcz * m2) - f(qaz * m0)) * dt)); vx2 = f(vx2 - f(f(f(qbx * m0) + f(qcx * m1)) * dt)); vy2 = f(vy2 - f(f(f(qby * m0) + f(qcy * m1)) * dt)); vz2 = f(vz2 - f(f(f(qbz * m0) + f(qcz * m1)) * dt)); x0 = f(x0 + f(vx0 * dt)); y0 = f(y0 + f(vy0 * dt)); z0 = f(z0 + f(vz0 * dt)); x1 = f(x1 + f(vx1 * dt)); y1 = f(y1 + f(vy1 * dt)); z1 = f(z1 + f(vz1 * dt)); x2 = f(x2 + f(vx2 * dt)); y2 = f(y2 + f(vy2 * dt)); z2 = f(z2 + f(vz2 * dt)); } const s0 = f(f(vx0 * vx0) + f(f(vy0 * vy0) + f(vz0 * vz0))); const s1 = f(f(vx1 * vx1) + f(f(vy1 * vy1) + f(vz1 * vz1))); const s2 = f(f(vx2 * vx2) + f(f(vy2 * vy2) + f(vz2 * vz2))); const k0 = f(f(f(0.5) * m0) * s0); const k1 = f(f(f(0.5) * m1) * s1); const k2 = f(f(f(0.5) * m2) * s2); const ke = f(k0 + f(k1 + k2)); const ax = f(x1 - x0), ay = f(y1 - y0), az = f(z1 - z0); const da = f(f(f(ax * ax) + f(f(ay * ay) + f(az * az))) + eps); const bx = f(x2 - x0), by = f(y2 - y0), bz = f(z2 - z0); const db = f(f(f(bx * bx) + f(f(by * by) + f(bz * bz))) + eps); const cx = f(x2 - x1), cy = f(y2 - y1), cz = f(z2 - z1); const dc = f(f(f(cx * cx) + f(f(cy * cy) + f(cz * cz))) + eps); const pa = f(f(m0 * m1) / f(Math.sqrt(da))); const pb = f(f(m0 * m2) / f(Math.sqrt(db))); const pc = f(f(m1 * m2) / f(Math.sqrt(dc))); const pe = f(pa + f(pb + pc)); const e = f(ke - pe); const nb = float_word(f(0 - e)); const eb = nb > 7 ? 7 : nb; const w0 = (Math.imul(float_word(f(f(x0 + 8) * 65536)), 31) + float_word(f(f(y0 + 8) * 65536))) >>> 0; const w1 = (Math.imul(float_word(f(f(x1 + 8) * 65536)), 31) + float_word(f(f(y1 + 8) * 65536))) >>> 0; const w2 = (Math.imul(float_word(f(f(x2 + 8) * 65536)), 31) + float_word(f(f(y2 + 8) * 65536))) >>> 0; const w3 = (Math.imul(float_word(f(f(z0 + 8) * 65536)), 31) + float_word(f(f(z1 + 8) * 65536))) >>> 0; const w4 = (Math.imul(w0, 2654435761) + w1) >>> 0; const w5 = (Math.imul(w4, 2654435761) + w2) >>> 0; const w6 = (Math.imul(w5, 2654435761) + w3) >>> 0; const cs = (Math.imul(w6, 2654435761) + float_word(f(f(z2 + 8) * 65536))) >>> 0; return [cs, eb]; } const count = 8 << SY; const h = new Uint32Array(8); let sum = 0; for (let sd = 0; sd < count; sd++) { const [cs, eb] = system_run(sd, ST); h[eb]++; sum = (sum + Math.imul(cs, (Math.imul(sd, 2654435761) + 1) >>> 0)) >>> 0; } let g = h[0]; for (let k = 1; k < 8; k++) g = (Math.imul(g, 2654435761) + h[k]) >>> 0; console.log((Math.imul(g, 2654435761) + sum) >>> 0); - bench/runtime/queens/main.ts (3070 bytes)
// Single-threaded TypeScript twin of main.bend. Same // algorithm, same shape: 4-row prefix decode + bitmask legality, then // the bitmask backtracker over the remaining rows threading per-branch // Stats{sols, nodes}; the Bend fork tree's smerge reduction is a plain // sum over the prefix index space. Same recursive backtracker as the // Bend bench. Checksum = (sols * 2654435761) ^ nodes. // Expected at SIZE=17, LIMIT=11730: 2063750025 (SIZE=8, LIMIT=512: // 2027808349). const SIZE = 17, LIMIT = 11730, DEPTH = 17; class Stats { sols: number; nodes: number; constructor(sols: number, nodes: number) { this.sols = sols; this.nodes = nodes; } } function board_solve( cand: number, cols: number, ldiag: number, rdiag: number, full: number, sols: number, nodes: number, ): Stats { cand >>>= 0; while (cand !== 0) { const bit = (cand & -cand) >>> 0, nextCols = (cols | bit) >>> 0; if (nextCols === full) { sols = (sols + 1) >>> 0; nodes = (nodes + 1) >>> 0; } else { const nextLeft = ((ldiag | bit) << 1) >>> 0, nextRight = (rdiag | bit) >>> 1; const w = board_solve( (full & ~(nextCols | nextLeft | nextRight)) >>> 0, nextCols, nextLeft, nextRight, full, sols, (nodes + 1) >>> 0, ); sols = w.sols; nodes = w.nodes; } cand = (cand - bit) >>> 0; } return new Stats(sols, nodes); } // one 4-row prefix: decode the column quad, filter illegal placements, // solve the remaining rows function prefix_solve( j: number, nn: number, full: number, bound: number, ): Stats { // fork-order permutation (bijection on the 2^17 space) const i = (Math.imul(j, 2654435761) & 131071) >>> 0; if (!(i < bound)) { return new Stats(0, 0); } const nn2 = nn * nn; const b0 = (1 << Math.trunc(i / (nn2 * nn))) >>> 0, b1 = (1 << Math.trunc(i / nn2) % nn) >>> 0; if ((b1 & (b0 | (b0 << 1) | (b0 >>> 1))) !== 0) { return new Stats(0, 0); } const b2 = (1 << Math.trunc(i / nn) % nn) >>> 0, c2 = (b0 | b1) >>> 0; const l2 = (((b0 << 1) | b1) << 1) >>> 0, r2 = ((b0 >>> 1) | b1) >>> 1; if ((b2 & (c2 | l2 | r2)) !== 0) { return new Stats(0, 0); } const b3 = (1 << i % nn) >>> 0, c3 = (c2 | b2) >>> 0; const l3 = ((l2 | b2) << 1) >>> 0, r3 = (r2 | b2) >>> 1; if ((b3 & (c3 | l3 | r3)) !== 0) { return new Stats(0, 0); } const c4 = (c3 | b3) >>> 0, l4 = ((l3 | b3) << 1) >>> 0, r4 = (r3 | b3) >>> 1; return board_solve((full & ~(c4 | l4 | r4)) >>> 0, c4, l4, r4, full, 0, 0); } function benchmark_run(): number { const nn = SIZE, full = ((1 << nn) - 1) >>> 0, nn2 = nn * nn, nnnn = nn2 * nn2; const bound = LIMIT < nnnn ? LIMIT : nnnn; let sols = 0, nodes = 0; for (let i = 0; i < 1 << DEPTH; ++i) { const s = prefix_solve(i, nn, full, bound); sols = (sols + s.sols) >>> 0; nodes = (nodes + s.nodes) >>> 0; } return (Math.imul(sols, 2654435761) ^ nodes) >>> 0; } console.log(benchmark_run()); - bench/runtime/raytrace/main.ts (5406 bytes)
// Single-threaded TypeScript twin of main.bend. // Same scene of 9 spheres + one point light at (-3,8,1), same 2x2 // supersampled pixels, nearest-hit + Lambertian shadow shading + // mirror bounce on a countdown depth (4). ray_trace is in the bench's // accumulator form: per bounce acc' = acc + ((w*lum)*(1-kr)), w' = // w*kr, final level adds acc + (w*lum); nearest folds spheres 8 down // to 0 with strict <. Math.fround at every primitive operation // preserves Bend's one-operation f32 semantics; the Bend row-fork // reduction is a plain row loop (u32 wrapping sum). // Expected at ROWS=12, WIDTH=6000: 1924309504 (ROWS=6, WIDTH=80: // 402971). const ROWS = 12, WIDTH = 6000, NS = 9, DEPTH = 4; type Sphere = readonly [number, number, number, number, number]; const SPHERES: readonly Sphere[] = [ [0, -10001, 5, 10000, 0.3], [0, 0, 5, 1, 0.7], [2, 0.5, 6, 1, 0.4], [-2, 0.5, 6, 1, 0.4], [1, -0.6, 3.5, 0.4, 0.9], [-1, -0.6, 3.5, 0.4, 0.9], [0, 1.6, 7, 1.2, 0.1], [3.5, 0.2, 8, 1, 0.6], [-3.5, 0.2, 8, 1, 0.6], ].map((s) => s.map(Math.fround) as unknown as Sphere); const fadd = (a: number, b: number) => Math.fround(Math.fround(a) + Math.fround(b)); const fsub = (a: number, b: number) => Math.fround(Math.fround(a) - Math.fround(b)); const fmul = (a: number, b: number) => Math.fround(Math.fround(a) * Math.fround(b)); const fdiv = (a: number, b: number) => Math.fround(Math.fround(a) / Math.fround(b)); const fsqrt = (a: number) => Math.fround(Math.sqrt(a)); function sphere_isect( i: number, ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, ): number { const s = SPHERES[i], px = fsub(ox, s[0]), py = fsub(oy, s[1]), pz = fsub(oz, s[2]); const b = fadd(fadd(fmul(px, dx), fmul(py, dy)), fmul(pz, dz)); const c = fsub( fadd(fadd(fmul(px, px), fmul(py, py)), fmul(pz, pz)), fmul(s[3], s[3]), ); const disc = fsub(fmul(b, b), c); if (disc < 0) { return 1e9; } const t = fsub(fsub(0, b), fsqrt(disc)); return t < 0.001 ? 1e9 : t; } function scene_nearest( ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, ): [number, number] { let best = 1e9, id = NS; for (let i = NS; i > 0; --i) { const t = sphere_isect(i - 1, ox, oy, oz, dx, dy, dz); if (t < best) { best = t; id = i - 1; } } return [best, id]; } function ray_trace( dep: number, ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, acc: number, w: number, ): number { const [t, id] = scene_nearest(ox, oy, oz, dx, dy, dz); if (id === NS) { return acc; } const s = SPHERES[id], hx = fadd(ox, fmul(t, dx)), hy = fadd(oy, fmul(t, dy)), hz = fadd(oz, fmul(t, dz)); const nx = fdiv(fsub(hx, s[0]), s[3]), ny = fdiv(fsub(hy, s[1]), s[3]), nz = fdiv(fsub(hz, s[2]), s[3]); const lvx = fsub(-3, hx), lvy = fsub(8, hy), lvz = fsub(1, hz); const ll = fsqrt(fadd(fadd(fmul(lvx, lvx), fmul(lvy, lvy)), fmul(lvz, lvz))); const lx = fdiv(lvx, ll), ly = fdiv(lvy, ll), lz = fdiv(lvz, ll); const dot = fadd(fadd(fmul(nx, lx), fmul(ny, ly)), fmul(nz, lz)), df = dot < 0 ? 0 : dot; const sox = fadd(hx, fmul(0.001, nx)), soy = fadd(hy, fmul(0.001, ny)), soz = fadd(hz, fmul(0.001, nz)); const [shadow] = scene_nearest(sox, soy, soz, lx, ly, lz), shade = shadow < ll ? 0 : df; const lum = fadd(0.1, fmul(0.85, shade)); if (dep === 0) { return fadd(acc, fmul(w, lum)); } const k2 = fmul(2, fadd(fadd(fmul(dx, nx), fmul(dy, ny)), fmul(dz, nz))); return ray_trace( dep - 1, sox, soy, soz, fsub(dx, fmul(k2, nx)), fsub(dy, fmul(k2, ny)), fsub(dz, fmul(k2, nz)), fadd(acc, fmul(fmul(w, lum), fsub(1, s[4]))), fmul(w, s[4]), ); } function ray_sub(fx: number, fy: number): number { const dl = fsqrt(fadd(fadd(fmul(fx, fx), fmul(fy, fy)), 1)); return ray_trace( DEPTH, 0, 0, 0, fdiv(fx, dl), fdiv(fy, dl), fdiv(1, dl), 0, 1, ); } // 2x2 supersampled pixel function pixel_render(x: number, y: number, hw: number, hh: number): number { const xf = Math.fround(x), yf = Math.fround(y); const l1 = ray_sub( fdiv(fsub(fadd(xf, 0.25), hw), hw), fdiv(fsub(hh, fadd(yf, 0.25)), hw), ); const l2 = ray_sub( fdiv(fsub(fadd(xf, 0.75), hw), hw), fdiv(fsub(hh, fadd(yf, 0.25)), hw), ); const l3 = ray_sub( fdiv(fsub(fadd(xf, 0.25), hw), hw), fdiv(fsub(hh, fadd(yf, 0.75)), hw), ); const l4 = ray_sub( fdiv(fsub(fadd(xf, 0.75), hw), hw), fdiv(fsub(hh, fadd(yf, 0.75)), hw), ); const avg = fmul(fadd(fadd(l1, l2), fadd(l3, l4)), 0.25); return Math.trunc(fmul(255, avg < 0 ? 0 : avg > 1 ? 1 : avg)) >>> 0; } function benchmark_run(): number { const h = 1 << ROWS, hw = Math.fround(Math.trunc(WIDTH / 2)), hh = Math.fround(Math.trunc(h / 2)); let acc = 0; // the Bend fork tree permutes row/column indices by odd multipliers // (bijections: same pixel set, same u32 sum); mirrored here for (let yj = 0; yj < h; ++yj) { const y = (Math.imul(yj, 1588635697) & (h - 1)) >>> 0; for (let xj = 0; xj < 16384; ++xj) { const x = (Math.imul(xj, 2654435761) & 16383) >>> 0; if (x < WIDTH) { acc = (acc + pixel_render(x, y, hw, hh)) >>> 0; } } } return acc; } console.log(benchmark_run()); - bench/runtime/symreg/main.ts (4625 bytes)
// Single-threaded TypeScript twin of main.bend. Same // algorithms over the same expression-tree ADT: expr_gen materializes // each depth-5 candidate AST from the xorshift32 stream (plain class // nodes), expr_eval is the recursive pattern-matching interpreter // (Bend's eval walks the tree; value recursion, order and u32 // numerics are identical), expr_size adds the // parsimony penalty, batch_run folds the tournament, seed_climb // hill-climbs the winner. Checksum printed as one u32. // Expected at SIZE=18, PTS=110: 2383953211. const SIZE = 18, PTS = 110, ROUNDS = 32; const EXPR_VAR = 0, EXPR_LIT = 1, EXPR_ADD = 2, EXPR_SUB = 3, EXPR_MUL = 4, EXPR_XOR = 5; class Expr { tag: number; v: number; a: Expr | null; b: Expr | null; constructor(tag: number, v: number, a: Expr | null, b: Expr | null) { this.tag = tag; this.v = v; this.a = a; this.b = b; } } function word_prng(x: number): number { const b = (x ^ (x << 13)) >>> 0; const d = (b ^ (b >>> 17)) >>> 0; return (d ^ (d << 5)) >>> 0; } function value_select(t: number, x: number, y: number): number { return t === 0 ? x : y; } function value_difference(a: number, b: number): number { return value_select(a < b ? 1 : 0, (a - b) >>> 0, (b - a) >>> 0); } // materialize a candidate AST straight off the hash stream function expr_gen(d: number, h: number): Expr { if (d === 0) { if (((h >>> 8) & 1) === 0) { return new Expr(EXPR_VAR, 0, null, null); } return new Expr(EXPR_LIT, h & 255, null, null); } const a = expr_gen(d - 1, word_prng((h ^ 2654435761) >>> 0)); const b = expr_gen(d - 1, word_prng((h + 340573321) >>> 0)); switch (h % 4) { case 0: return new Expr(EXPR_ADD, 0, a, b); case 1: return new Expr(EXPR_SUB, 0, a, b); case 2: return new Expr(EXPR_MUL, 0, a, b); default: return new Expr(EXPR_XOR, 0, a, b); } } // pattern-matching interpreter: value of the candidate at x function expr_eval(e: Expr, x: number): number { switch (e.tag) { case EXPR_VAR: return x; case EXPR_LIT: return e.v; case EXPR_ADD: return (expr_eval(e.a!, x) + expr_eval(e.b!, x)) >>> 0; case EXPR_SUB: return (expr_eval(e.a!, x) - expr_eval(e.b!, x)) >>> 0; case EXPR_MUL: return Math.imul(expr_eval(e.a!, x), expr_eval(e.b!, x)) >>> 0; default: return (expr_eval(e.a!, x) ^ expr_eval(e.b!, x)) >>> 0; } } // parsimony: AST node count function expr_size(e: Expr): number { if (e.tag === EXPR_VAR || e.tag === EXPR_LIT) { return 1; } return (1 + ((expr_size(e.a!) + expr_size(e.b!)) >>> 0)) >>> 0; } // dataset fold: error sum over x = 0..j-1, then the parsimony penalty function fitness_loop(j: number, e: Expr, acc: number): number { while (j !== 0) { const x = j - 1; const p = expr_eval(e, x); const t = (Math.imul(x, x) + (Math.imul(3, x) + 7)) >>> 0; acc = (acc + value_difference(p, t)) >>> 0; j = x; } return (acc + Math.imul(expr_size(e), 8)) >>> 0; } class Sel { fit: number; seed: number; sum: number; constructor(fit: number, seed: number, sum: number) { this.fit = fit; this.seed = seed; this.sum = sum; } } function candidate_evaluate(s: number, pts: number): Sel { const t = expr_gen(5, word_prng(s)); const f = fitness_loop(pts, t, 0); return new Sel(f, s, (f ^ Math.imul(s, 2654435761)) >>> 0); } // tournament: keep the lower-fitness candidate, sum the checksums function winner_pick(a: Sel, b: Sel): Sel { const w = a.fit < b.fit ? 1 : 0; return new Sel( value_select(w, b.fit, a.fit), value_select(w, b.seed, a.seed), (a.sum + b.sum) >>> 0, ); } function batch_run(d: number, s: number, pts: number): Sel { if (d === 0) { return candidate_evaluate(word_prng(s), pts); } const a = batch_run(d - 1, (Math.imul(s, 1664525) + 1) >>> 0, pts); const b = batch_run(d - 1, (Math.imul(s, 214013) + 3) >>> 0, pts); return winner_pick(a, b); } // hill-climb the tournament winner: mutate the seed, keep improvements function seed_climb(r: number, bs: number, bf: number, pts: number): number { while (r !== 0) { const w0 = candidate_evaluate( word_prng((bs ^ Math.imul(r, 40503)) >>> 0), pts, ); const w = w0.fit < bf ? 1 : 0; bs = value_select(w, bs, w0.seed); bf = value_select(w, bf, w0.fit); r -= 1; } return (bf ^ Math.imul(bs, 2654435761)) >>> 0; } function benchmark_run(): number { const w1 = batch_run(SIZE, 42, PTS); return (seed_climb(ROUNDS, w1.seed, w1.fit, PTS) + w1.sum) >>> 0; } console.log(benchmark_run()); - bench/runtime/terrain/main.ts (3619 bytes)
// Native TypeScript twin of main.bend: procedural terrain tile // pipeline. Same value-noise fill, in-place Gauss-Seidel relaxation sweeps // with pass-salted roughening, 64-bin histogram and position-weighted // folds, wrapping-u32 numerics (imul + >>>0; heightmaps are Uint32Arrays). const word_wrap = (value: number): number => value >>> 0; function word_prng(x: number): number { const b = word_wrap(x ^ (x << 13)); const d = word_wrap(b ^ (b >>> 17)); return word_wrap(d ^ (d << 5)); } // lattice corner hash -> 0..255 function lattice_hash(gx: number, gz: number): number { return word_prng(word_wrap(Math.imul(gx, 2654435761) ^ Math.imul(gz, 340573321))) & 255; } // value noise at 8.8 fixed-point (x, z): bilinear lerp of 4 corner hashes function terrain_ground(x: number, z: number): number { const gx = (x >>> 8) & 63; const gz = (z >>> 8) & 63; const fx = x & 255; const fz = z & 255; const gx1 = (gx + 1) & 63; const gz1 = (gz + 1) & 63; const h00 = lattice_hash(gx, gz); const h10 = lattice_hash(gx1, gz); const h01 = lattice_hash(gx, gz1); const h11 = lattice_hash(gx1, gz1); const t0 = (h00 * (256 - fx) + h10 * fx) >>> 8; const t1 = (h01 * (256 - fx) + h11 * fx) >>> 8; return (t0 * (256 - fz) + t1 * fz) >>> 8; } // noise-fill one tile: one write per cell function tile_fill(ox: number, oz: number, h: Uint32Array): void { for (let i = 0; i < 4096; i++) { h[i] = terrain_ground(word_wrap((ox + (i & 63)) << 6), word_wrap((oz + (i >>> 6)) << 6)); } } // one relaxation cell: 5 reads + 1 write, clamped neighbours, // pass-salted 1-bit roughening function erode_cell(i: number, p: number, h: Uint32Array): void { const xc = i & 63; const zc = i >>> 6; const hc = h[i]; const hl = h[i - (xc > 0 ? 1 : 0)]; const hr = h[i + (xc < 63 ? 1 : 0)]; const hu = h[i - ((zc > 0 ? 1 : 0) << 6)]; const hd = h[i + ((zc < 63 ? 1 : 0) << 6)]; const rough = word_prng(word_wrap(i ^ word_wrap(Math.imul(p, 2654435761)))) & 1; h[i] = word_wrap(((word_wrap(hc * 4 + hl + hr + hu + hd)) >>> 3) + rough); } // one Gauss-Seidel sweep over the tile, ascending scan order function tile_erode(p: number, h: Uint32Array): void { for (let i = 0; i < 4096; i++) { erode_cell(i, p, h); } } function tile_smooth(p: number, h: Uint32Array): void { while (p !== 0) { tile_erode(p, h); p--; } } // histogram fold: mix every bucket count, position-weighted function hist_fold(g: Uint32Array, acc: number): number { for (let i = 0; i < 64; i++) { acc = word_wrap(Math.imul(acc, 2654435761) ^ word_wrap(Math.imul(g[i], i + 3))); } return acc; } // per cell: read the height, bump its histogram bucket, mix the height function tile_hist(h: Uint32Array, g: Uint32Array, acc: number): number { for (let i = 0; i < 4096; i++) { const v = h[i]; const b = (v >>> 2) & 63; g[b] = word_wrap(g[b] + 1); acc = word_wrap(Math.imul(acc, 2654435761) + Math.imul(v, i + 1)); } return hist_fold(g, acc); } // one tile: fill, EPASS relaxation sweeps, histogram + fold function tile_run(t: number, e: number): number { const h = new Uint32Array(4096); const g = new Uint32Array(64); const ox = word_wrap((t & 255) << 6); const oz = word_wrap((t >>> 8) << 6); tile_fill(ox, oz, h); tile_smooth(e, h); return tile_hist(h, g, word_wrap(t + 1)); } function batch_run(d: number, t: number, e: number): number { if (d === 0) { return tile_run(t, e); } const a = batch_run(d - 1, t, e); const b = batch_run(d - 1, word_wrap(t + (1 << (d - 1))), e); return word_wrap(a + b); } console.log(batch_run(16, 0, 5)); - bench/runtime/tree-bitonic/main.ts (2956 bytes)
// TypeScript twin of main.bend: same tree-shaped bitonic sorting // network, key generator and Stat verification scan, single-threaded. // Tree nodes are class instances (monomorphic shapes); the GC plays the // role of the linear frees. class Leaf { v: number; constructor(v: number) { this.v = v; } } class Fork { l: Tree; r: Tree; constructor(l: Tree, r: Tree) { this.l = l; this.r = r; } } type Tree = Leaf | Fork; type Stat = { lo: number; hi: number; ok: number; mx: number }; const SIZE = 23; function word_prng(x: number): number { const b = (x ^ (x << 13)) >>> 0; const d = (b ^ (b >>> 17)) >>> 0; return (d ^ (d << 5)) >>> 0; } function word_key(i: number): number { return word_prng(Math.imul(i + 1, 2654435761) >>> 0); } function tree_swap(s: number, a: number, b: number): Tree { return s === 0 ? new Fork(new Leaf(a), new Leaf(b)) : new Fork(new Leaf(b), new Leaf(a)); } function tree_warp_zip(wa: Tree, wb: Tree): Tree { if (wa instanceof Fork && wb instanceof Fork) { return new Fork(new Fork(wa.l, wb.l), new Fork(wa.r, wb.r)); } return new Leaf(0); } function tree_warp(s: number, a: Tree, b: Tree): Tree { if (a instanceof Leaf && b instanceof Leaf) { return tree_swap(s ^ (a.v > b.v ? 1 : 0), a.v, b.v); } if (a instanceof Fork && b instanceof Fork) { return tree_warp_zip(tree_warp(s, a.l, b.l), tree_warp(s, a.r, b.r)); } return new Leaf(0); } // mode 0 warps the halves, mode 1 descends one level shallower function tree_flow(d: number, m: number, s: number, t: Tree): Tree { if (d === 0) return t; if (m === 0) { if (!(t instanceof Fork)) return t; return tree_flow(d - 1, 1, s, tree_warp(s, t.l, t.r)); } if (!(t instanceof Fork)) return t; return new Fork(tree_flow(d, 0, s, t.l), tree_flow(d, 0, s, t.r)); } function tree_sort_1(d: number, s: number, sa: Tree, sb: Tree): Tree { return tree_flow(d, 0, s, new Fork(sa, sb)); } function tree_bsort(d: number, s: number, x: number): Tree { if (d === 0) return new Leaf(word_key(x)); const sa = tree_bsort(d - 1, 0, (x * 2 + 1) >>> 0); const sb = tree_bsort(d - 1, 1, (x * 2) >>> 0); return tree_sort_1(d, s, sa, sb); } function stat_join(a: Stat, b: Stat): Stat { return { lo: a.lo, hi: b.hi, ok: a.ok & b.ok & (a.hi <= b.lo ? 1 : 0), mx: (Math.imul(a.mx, 2654435761) + b.mx) >>> 0, }; } function tree_scan(d: number, t: Tree): Stat { if (d === 0) { const v = t instanceof Leaf ? t.v : 0; return { lo: v, hi: v, ok: 1, mx: v }; } if (!(t instanceof Fork)) return { lo: 0, hi: 0, ok: 0, mx: 0 }; return stat_join(tree_scan(d - 1, t.l), tree_scan(d - 1, t.r)); } function stat_out(s: Stat): number { return ( (((Math.imul(s.mx, 2654435761) >>> 0) ^ ((s.hi + Math.imul(s.lo, 340573321)) >>> 0)) + Math.imul(s.ok, 2246822519)) >>> 0 ); } const t = tree_bsort(SIZE, 0, 0); console.log(stat_out(tree_scan(SIZE, t))); - bench/runtime/tree-matmul/main.ts (4710 bytes)
// Native TypeScript twin of main.bend: recursive block matrix multiply // over quad-trees with a Freivalds verification pass. Same datatypes, // algorithms and wrapping-u32 numerics (imul + >>>0). const word_wrap = (value: number): number => value >>> 0; type Mat = { v: number; k: Mat[] | null }; type Vec = Mat; function node_leaf(v: number): Mat { return { v, k: null }; } function mat_quad(a: Mat, b: Mat, c: Mat, d: Mat): Mat { return { v: 0, k: [a, b, c, d] }; } function vec_branch(l: Vec, r: Vec): Vec { return { v: 0, k: [l, r] }; } function mat_gen(d: number, s: number): Mat { if (d === 0) { return node_leaf(s % 100); } const a = mat_gen(d - 1, word_wrap(Math.imul(s, 1664525) + 1)); const b = mat_gen(d - 1, word_wrap(Math.imul(s, 214013) + 3)); const c = mat_gen(d - 1, word_wrap(Math.imul(s, 16843009) + 5)); const e = mat_gen(d - 1, word_wrap(Math.imul(s, 48271) + 7)); return mat_quad(a, b, c, e); } function vec_gen(d: number, s: number): Vec { if (d === 0) { return node_leaf((word_wrap(Math.imul(s, 2654435761)) % 100) + 1); } const l = vec_gen(d - 1, word_wrap(Math.imul(s, 1664525) + 1)); const r = vec_gen(d - 1, word_wrap(Math.imul(s, 214013) + 3)); return vec_branch(l, r); } function mat_add(a: Mat, b: Mat): Mat { if (a.k === null) { return node_leaf(word_wrap(a.v + (b.k === null ? b.v : 0))); } if (b.k === null) { return node_leaf(0); } const r0 = mat_add(a.k[0], b.k[0]); const r1 = mat_add(a.k[1], b.k[1]); const r2 = mat_add(a.k[2], b.k[2]); const r3 = mat_add(a.k[3], b.k[3]); return mat_quad(r0, r1, r2, r3); } // join of one mul burst: C_ij = P_ij + Q_ij function mat_add4( p0: Mat, q0: Mat, p1: Mat, q1: Mat, p2: Mat, q2: Mat, p3: Mat, q3: Mat, ): Mat { return mat_quad(mat_add(p0, q0), mat_add(p1, q1), mat_add(p2, q2), mat_add(p3, q3)); } // each node spawns its whole 8-product burst, joined through mat_add4 function mat_mul(a: Mat, b: Mat): Mat { if (a.k === null) { return node_leaf(b.k === null ? word_wrap(Math.imul(a.v, b.v)) : 0); } if (b.k === null) { return node_leaf(0); } const p0 = mat_mul(a.k[0], b.k[0]); const q0 = mat_mul(a.k[1], b.k[2]); const p1 = mat_mul(a.k[0], b.k[1]); const q1 = mat_mul(a.k[1], b.k[3]); const p2 = mat_mul(a.k[2], b.k[0]); const q2 = mat_mul(a.k[3], b.k[2]); const p3 = mat_mul(a.k[2], b.k[1]); const q3 = mat_mul(a.k[3], b.k[3]); return mat_add4(p0, q0, p1, q1, p2, q2, p3, q3); } function vec_add(x: Vec, y: Vec): Vec { if (x.k === null) { return node_leaf(y.k === null ? word_wrap(x.v + y.v) : 0); } if (y.k === null) { return node_leaf(0); } return vec_branch(vec_add(x.k[0], y.k[0]), vec_add(x.k[1], y.k[1])); } // join of one mvm burst function vec_add2(t0: Vec, t1: Vec, t2: Vec, t3: Vec): Vec { return vec_branch(vec_add(t0, t1), vec_add(t2, t3)); } // [[a,b],[c,d]] * (l,h) = (a*l + b*h, c*l + d*h) function mat_vec_mul(m: Mat, v: Vec): Vec { if (m.k === null) { return node_leaf(v.k === null ? word_wrap(Math.imul(m.v, v.v)) : 0); } if (v.k === null) { return node_leaf(0); } const t0 = mat_vec_mul(m.k[0], v.k[0]); const t1 = mat_vec_mul(m.k[1], v.k[1]); const t2 = mat_vec_mul(m.k[2], v.k[0]); const t3 = mat_vec_mul(m.k[3], v.k[1]); return vec_add2(t0, t1, t2, t3); } function mat_cksum(m: Mat): number { if (m.k === null) { return m.v; } return word_wrap( mat_cksum(m.k[0]) + mat_cksum(m.k[1]) + mat_cksum(m.k[2]) + mat_cksum(m.k[3]), ); } // or-fold of elementwise xor: 0 iff the vectors are identical function vec_dif(x: Vec, y: Vec): number { if (x.k === null || y.k === null) { return x.k === null && y.k === null ? word_wrap(x.v ^ y.v) : 1; } return word_wrap(vec_dif(x.k[0], y.k[0]) | vec_dif(x.k[1], y.k[1])); } // one round: generate A, B, r; C = A*B; Freivalds-verify C*r == A*(B*r) function round_run(d: number, s: number): number { const a = mat_gen(d, word_wrap(s + 1)); const b = mat_gen(d, word_wrap(s + 2)); const r = vec_gen(d, word_wrap(s + 3)); const c = mat_mul(a, b); const k = mat_cksum(c); const t1 = mat_vec_mul(c, r); const u = mat_vec_mul(b, r); const t2 = mat_vec_mul(a, u); const v = vec_dif(t1, t2); return word_wrap(word_wrap(k ^ word_wrap(Math.imul(s, 2654435761))) + (v === 0 ? 1 : 0)); } // batch over the round index space: round i runs on seed = hashed index // (u32 addition commutes, so the flat loop equals the Bend fork tree) function batch_run(nchain: number, d: number): number { let acc = 0; for (let i = 0; i < nchain; i++) { acc = word_wrap(acc + round_run(d, word_wrap(Math.imul(i, 2654435761)))); } return acc; } console.log(batch_run(384, 7)); - bench/runtime/tree-radix/main.ts (3384 bytes)
// TypeScript twin of main.bend: same trie sort (gen -> // to_map/merge -> to_arr) and Chk verification scan, single-threaded. // ADT nodes are class instances (monomorphic shapes); the GC plays the // role of the linear frees. class ArrEmpty {} class ArrSingle { v: number; constructor(v: number) { this.v = v; } } class ArrConcat { l: Arr; r: Arr; constructor(l: Arr, r: Arr) { this.l = l; this.r = r; } } type Arr = ArrEmpty | ArrSingle | ArrConcat; class MapFree {} class MapBusy {} class MapNode { l: MapTree; r: MapTree; constructor(l: MapTree, r: MapTree) { this.l = l; this.r = r; } } type MapTree = MapFree | MapBusy | MapNode; type Chk = { nil: number; lo: number; hi: number; ok: number; cnt: number; sum: number; }; const DEPTH = 22; function word_prng(x: number): number { const b = (x ^ (x << 13)) >>> 0; const d = (b ^ (b >>> 17)) >>> 0; return (d ^ (d << 5)) >>> 0; } function word_key(i: number): number { return word_prng(Math.imul(i + 1, 2654435761) >>> 0) & 16777215; } function map_merge(a: MapTree, b: MapTree): MapTree { if (a instanceof MapFree) return b; if (b instanceof MapFree) return a; if (a instanceof MapBusy || b instanceof MapBusy) return new MapBusy(); const an = a as MapNode; const bn = b as MapNode; return new MapNode(map_merge(an.l, bn.l), map_merge(an.r, bn.r)); } function arr_generate(n: number, x: number): Arr { if (n === 0) return new ArrSingle(word_key(x)); return new ArrConcat( arr_generate(n - 1, (x * 2) >>> 0), arr_generate(n - 1, (x * 2 + 1) >>> 0), ); } function map_swap_bits(n: number, x0: MapTree, x1: MapTree): MapTree { return n === 0 ? new MapNode(x0, x1) : new MapNode(x1, x0); } function map_radix(i: number, n: number, k: number, r: MapTree): MapTree { while (i) { r = map_swap_bits(n & k, r, new MapFree()); k = (k * 2) >>> 0; i--; } return r; } function arr_to_map(a: Arr): MapTree { if (a instanceof ArrEmpty) return new MapFree(); if (a instanceof ArrSingle) return map_radix(24, a.v, 1, new MapBusy()); const c = a as ArrConcat; return map_merge(arr_to_map(c.l), arr_to_map(c.r)); } function map_to_arr(m: MapTree, k: number): Arr { if (m instanceof MapFree) return new ArrEmpty(); if (m instanceof MapBusy) return new ArrSingle(k); const n = m as MapNode; return new ArrConcat( map_to_arr(n.l, (k * 2) >>> 0), map_to_arr(n.r, (k * 2 + 1) >>> 0), ); } function chk_join(a: Chk, b: Chk): Chk { if (a.nil) return b; if (b.nil) return a; return { nil: 0, lo: a.lo, hi: b.hi, ok: a.ok & b.ok & (a.hi < b.lo ? 1 : 0), cnt: (a.cnt + b.cnt) >>> 0, sum: (a.sum + b.sum) >>> 0, }; } function arr_chk(a: Arr): Chk { if (a instanceof ArrEmpty) return { nil: 1, lo: 0, hi: 0, ok: 0, cnt: 0, sum: 0 }; if (a instanceof ArrSingle) return { nil: 0, lo: a.v, hi: a.v, ok: 1, cnt: 1, sum: a.v }; const c = a as ArrConcat; return chk_join(arr_chk(c.l), arr_chk(c.r)); } function chk_out(c: Chk): number { if (c.nil) return 0; return ( ((((c.sum + Math.imul(c.cnt, 2654435761)) >>> 0) ^ ((c.hi + Math.imul(c.lo, 340573321)) >>> 0)) + Math.imul(c.ok, 2246822519)) >>> 0 ); } function arr_sort(a: Arr): Arr { return map_to_arr(arr_to_map(a), 0); } console.log(chk_out(arr_chk(arr_sort(arr_generate(DEPTH, 0))))); - bend2/bend.ts (144924 bytes)
// NOTE: this file was 99% human-designed and audited. // It includes Bend's trusted kernel, including interpreter and checker. // It has a bit of AI slop, but it is the most robust file in the repo. // // Bend // ==== // // SYNTAX // ------ // // Quant ::= // | "-" // | "" // | "+" // // Bind ::= // | Quant Name ":" Term // | "~" Name ":" Term // | Name // // Term ::= // | Var ::= Name // | Ref ::= Name // | Ann ::= "{" Term ":" Term "}" // | Typ ::= "Type" | "Data" | "Kind" "(" Term ")" // | Qnt ::= "Quant" // | Qua ::= "&0" | "&1" | "&2" // | Min ::= Term "<&>" Term // | All ::= "@" Bind "->" Term // | Lam ::= Name "=>" Body // | App ::= Term "(" [Term ","?] ")" // | ADT ::= Name "<" [Term ","?] ">" // | Ctr ::= Name "{" [Term ","?] "}" // | Mat ::= "\" "{" Name ":" Term ";"? Term "}" // | Efq ::= "\" "{" "}" // | Eql ::= "{" Term "==" Term ":" Term "}" // | Rfl ::= "{" "==" "}" // | Rwt ::= "%" (Name "@")? Term ":" Term ";"? Body // | Hol ::= "?" Name // | Grp ::= "(" Body ")" // // Case ::= "case" [Term] ":" Body // Match ::= "match" [Term] ":" [Case] // Local ::= (Quant Name | Term)+ "=" Term+ ";"? Body // Reply ::= Term // Body ::= Match | Local | Reply // Ctr ::= Name "{" [Bind ","?] "}" // ADT ::= "type" Name ("<" [Bind ","?] ">")? "is" Term ":" [Ctr] // Clause ::= ("for" (Quant | "~") | "exs") Name ":" Term ("where" Term)? // Law ::= "law" Name ":" [Clause] Body // Def ::= ("@unsafe")? "def" Name "?"? "(" [Bind ","?] ")" ("->" Term)? ":" (Body | ["import" STRING]+) // TLD ::= ADT | Law | Def // Import ::= "import" "Base" | "import" Path "as" Name (Path ends in .bend) // Book ::= [Import] [TLD] // // SUGARS // ------ // // Name | Grammar | Term // ------ | -------------------------- | ---- // Arrow | A "->" B | @_:A -> B // Exists | "&" Name ":" A "->" B | Exists(A, x => B) // Pair | A "&" B | Pair(A, B) // Or | A "|" B | Or(A, B) // Not | "{" a "!=" b ":" T "}" | {a == b : T} -> Empty // Tuple | "(" A ("," B)+ ")" | Tuple{A, Tuple{B, ..}} // List | "[" [A ","?] "]", A "<>" B | Con{A, ..Nil{}}, Con{A, B} // Array | "[" A ":" T ("*" 2^D "n" | "^" D) "]" | Array.new(T, D, A) // Nat | NUMBER "n" ("+" T)? | Lit, read as Succ{..Zero{}}; Succ{..T} // U32 | NUMBER | Lit, read as U32{WCon{b, ..WNil{}}} // F32 | NUMBER "." NUMBER [EXP] | Lit, read as F32{WCon{b, ..WNil{}}} // Chr | "'" CHAR "'" | Chr{U32}, its U32 a Lit // Str | "\"" [CHAR] "\"" | Lit, read as SCon{Chr, ..SNil{}} // Index | x "[" i "]" ("<-" v)? | Array.get(U32, x, i), ..set(..) // Fill | D "<" [A ","?] ">" | D<&1.., A..> // Plus | "+" D ("<" [A ","?] ">")? | D<&2.., A..> // Ops | "(" a "+" b ":" T ")" | T.add(a, b) // // every word the parser dispatches on is reserved and names nothing: // def, type, law, match, case, do, return, for, exs, where, // is, import, Type, Data, Kind, Quant ("as" reads only on an import // line and "unsafe" only after "@", so they stay free). // a file's namespace is its real path without ".bend", from the entry's // directory; a "0x<hash>/" path is its own namespace, read from BEND_LIB // and fetched from BEND_HUB on a miss; a "<name>@<version>/" path is the // hash the hub names it, kept under BEND_LIB/names. "as Name" binds a // per-file alias: Name.x resolves to the file's canonical name, so two // aliases of one file agree, and a def of an aliased name fills it. // "import Base" is the empty namespace; an unknown name is the file's own, // unless its bare spelling is Base's. // a def with no prior law types itself: a Bind telescope and a // "->" return type. a def after its law takes bare names, no "->". // "def f?(..)" is "@unsafe def f(..)". // a bare Bind name is -Name: Quant. Fill and Plus omit a datatype's // leading Quant parameters as a block; Plus alone fills a quant-only D. // a literal expands to one node per unit, unbounded by design, but a // number, a string and a char's code stay one Lit node and unfold where // a chain is read (a match, a comparison, a descent, a pattern); a full // word, a Nat, a Char, a String, a list, a tuple and an array (its // slots) print back as literals; "*" takes a power of two. Arrow is // right-associative; the domain of a written @ or & binder stops at the // first bare "->", so an arrow (or a nested binder) there needs parens. // infix "&" and "|" are right-associative, share one precedence, and // bind tighter than "->". a rewrite "%e@E : P; f" binds e and "_" inside // its motive P; "%E : P; f" is the nameless form: the equation binder is // spelled "" and cannot be referenced. // // an operator is a method with no namespace: the ": T" before the ")" // around it names T's head as its namespace, and nested parens // inherit, so (a + b * c : U32) is U32.add(a, U32.mul(b, c)) and an // argument is f((a + b : U32)); an index x[i + 1] is U32's; with no // parens it is refused; braces only annotate. || && ++ <> & | are // fixed, and equality is a call: T.is_eq(a, b). // // juxtaposition laws: a call or index suffix may be spaced but a // newline ends the spine. after a term, "<" takes one argument above // comparison level, then one token decides: ">" or "," commits to // type args (x<y>, X<A, B>), anything else is less-than -- so a // compound FIRST type argument needs parens (X<(A & B), C>; later // arguments are full terms). a glued // ">"-headed operator never fires -- space your comparisons and // shifts -- so nested closers stack (List<List<A>>). "-" or "+" glued // to a name heads a binder or literal, never an operator. a + on a // pattern, let, lambda or do binder x re-binds it reusable: +x = x // opens its body, below the destructures and match arms that head it. // statements // live in bodies: a def body, a case body, a lambda body or a // rewrite tail; parens hold one body, or a tuple. // a parallel let "x y z = a b c" is one Let binding n names to n // values, each checked in the outer scope; the compiler forks its // calls. a write a[i] <- v followed by a body statement is the let // a = a[i] <- v. one token after a parsed term decides, but a ": T" with // no "=" after it rewinds. // // "~k: T" heading a def's telescope, or "for ~k: T" in a law, makes it a // template: a call T(~a, ..) writes ~ before each ~ argument, or none; a // live closed call is the instance T~n, the def at a, minted and checked // when the call checks; an open one is refused, and a call in a type or // in a template's own text stays T's. // // Do-Notation // ----------- // // DoBlock ::= // | "do" Name "<" [Term ","?] ">" ":" [DoStmt] // // DoStmt ::= // | DoLet ::= Name ":" Term "=" Term ";"? DoStmt // | DoExec ::= Term "<-" Term ";"? DoStmt // | DoBind ::= Name ":" Term "<-" Term ";"? DoStmt // | DoStep ::= Term (";" | NEWLINE) DoStmt // | DoPure ::= "return" Term // | DoRetr ::= Term // // do M<ls.., R>: desugars onto M.bind(ls.., A, R, v, x => ..) and // M.pure(ls.., R, e); an empty list (do M<>:) drops R from both. A // step is Unit <- Term: a term is a step when a ";" or a line at the // block's column (its first statement's) follows it, else the value. // // THEORY // ------ // // Bend is a dependent affine calculus: two checking modes (dead and // live) and a well-founded descent judgment on live recursion. a live // variable is consumed at most once; a + binder licenses many uses and // forms only when its type is Data. every live self-call descends, and // no dead inhabitant is promoted to live evidence. this wall permits // Type : Type, impredicativity and negative recursive types with no // universe hierarchy and no positivity check: omega, Curry and Hurkens // each contract a live function-valued binding, and no function type // is Data. the gate is the wall. // quantities None | Lone | Many (-x, x, +x) add sequentially (two live // uses saturate to Many) and join pointwise-max across branches. the // demand qt is None (dead) or Lone (live), never Many: a term checked // at demand Many lets a binder inside it contract (McBride's system; // Atkey 2018, 2.3, shows it also breaks substitution). an argument to // a q binder checks at demand dem(q, qt), dead if q is -, else the // ambient demand, and its measure adds once, unscaled: certify-once. // so a Lone Data value may enter a + binder, let or field, and the // callee copies the value. QTT forbids this: a 1 never becomes an ω // (Atkey scales the argument's measure by the binder's ω), and a // linear value is copied only by walking it. QTT affords that because // its default is ω; Bend's default is Lone, so without promotion only // closed data would ever be reusable, and input only by an O(n) walk. // the price is a narrower theorem: term-substitution reduction does // not preserve the measure (unfold f(+x) at f(y): y counts twice under // its plain binder), so subject reduction for usage is claimed for // weak by-value reduction of closed terms, the only reduction the // machine performs: y is a value when f unfolds, its resources were // consumed once, and the copy is Data, which owns nothing by the gate. // three invariants outside the checker carry this: no pass duplicates // a term (wnf shares every argument, let value and field in a cell; // the compiler is strict); a type with runtime ownership (File, // Socket, Array) is Type, never Data; a compiler may drop a copy the // source spelled, never add one. // every type has a kind Kind(q) over a quantity q : Quant, &0 (None), // &1 (Lone) or &2 (Many); Type is Kind(&1), Data is Kind(&2), and a // - binder's domain checks at Kind(&0). term_compare (LE) orders // kinds by the quantity order with &0 and &1 one rung (a single use // is what every type affords): Kind(g) fits Kind(h) when h <= g, so // Data fits every kind, every kind fits Type and Kind(&0), and a meet // fits every kind under one of its sides, never else. a binder q x: A needs A to // fit Kind(q): its type's quantity is at least q. a function type // is Type (a closure captures), an equation is Data (evidence is // erased), a datatype declares its kind, Kind(G) over its parameters, // and the meet a <&> b is the minimum, reduced only when forced: &2 is // the identity, &0 absorbs, two literals meet, a stuck side stays // stuck, so no definition order can decide it early. both its operands // check at the ambient demand and their measures add, so a meet never // launders a live occurrence past the tally. book_valid earns // G: every live field's kind must fit Kind(G) in the real constructor // context, so a constructor-local quantity never reaches G and a // function field never sits in Data. // a type position, an erased (-) argument, an equality endpoint or a // motive checks dead: it may diverge and inhabit Empty; no rule coerces // dead to live. a +field is QTT's ω-tensor read the Bend way: it forms // only at Data, building it certifies its argument once, and matching // a Lone node still yields it Many; a -field is absent from storage // and dead; a pattern binder's quantity is its field's times its // scrutinee's; a + mark on a 1 binder over Data makes it +. // equality is intensional; elimination is the J axiom, %e@E : P; f, // and a stuck rewrite fires only when its evidence reaches {==}. // conversion is term_compare LE -- a fits b, a preorder, up to eta: // directional only at kinds and ADT residuals (removing more // constructors fits removing fewer), a function type compares its // domains swapped, and every part that flows both ways (an argument, // a parameter, a field, an equation endpoint) compares EQ. // every live self-call descends on a strict // subterm in its own case tree, live columns compared EQ left to right, // erased columns skipped. trusted claims: subject reduction (for // by-value reduction), progress, weak normalization of closed live // terms, no closed live inhabitant of Empty. // an @unsafe def opts out of the wall: its self-calls skip descent, its // binder domains form + at any kind, and it calls an unfilled law or a // def below it, so the claims above do not cover a book that uses one. // a hole ?name fails every check, // shown against the goal; ?TODO alone checks at any goal and marks // the book incomplete. import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import * as url from "node:url"; // Core // ==== // Types // ===== export type Bool = boolean; export type U32 = number; export type Name = string; export type Cmp = | "LT" | "EQ" | "GT"; // PMap export type PMap<Item> = | { $: "Emp" } | { $: "Bin"; v: Item | null; l: PMap<Item>; r: PMap<Item> }; // List export type List<Item> = { k: U32; v: Item; n: List<Item> } | null; // Quant export type Quant = | { $: "None" } | { $: "Lone" } | { $: "Many" }; // Uses export type Uses = PMap<Quant>; // Term export type BodyOf<B> = B extends [infer T] ? T : B; export type LetsOf<B> = BodyOf<B> extends Function ? (xs: TermOf<B>[]) => TermOf<B> : BodyOf<B>; export type SubsOf<B> = BodyOf<B> extends Function ? TermOf<NoInfer<B>> : HTerm; export type TermOf<B> = ( | { $: "Var"; k: Name; i: number; v?: SubsOf<B>; c?: Cell } // x | { $: "Ref"; k: Name; b?: Bool } // x | { $: "Sub"; i: number; v: Patt; f: TermOf<B> } // x <- v; f | { $: "Let"; k: Name[]; i: number[]; q: Quant[]; v: TermOf<B>[]; f: LetsOf<B> } // x y = v w; f | { $: "Typ"; g: TermOf<B> } // Kind(g) | { $: "Qnt" } // Quant | { $: "Qua"; q: Quant } // &1, &2 | { $: "Min"; a: TermOf<B>; b: TermOf<B> } // a <&> b | { $: "All"; q: Quant; k: Name; i: number; A: TermOf<B>; B: BodyOf<B> } // @x:A -> B | { $: "Lam"; k: Name; i: number; f: BodyOf<B>; q?: Quant } // x => f | { $: "App"; f: TermOf<B>; x: TermOf<B> } // f(x) | { $: "ADT"; k: Name; x: TermOf<B>[]; r: Name[] } // A<x0,x1,...> | { $: "Ctr"; k: Name; x: TermOf<B>[] } // A{x0,x1,...} | { $: "Lit"; k: "Nat" | "U32" | "F32"; v: number } // 3n, 7, 1.5 (its bits) | { $: "Lit"; k: "String"; v: string } // "text" | { $: "Mat"; k: Name; h: TermOf<B>; m: TermOf<B> } // \{A: h; m} | { $: "Efq" } // \{} | { $: "Eql"; a: TermOf<B>; b: TermOf<B>; T: TermOf<B> } // {a == b : T} | { $: "Rfl" } - bend2/comp.ts (190931 bytes)
// NOTE: Bend's runtime was designed by humans, but this file was mostly written // by AI's, as it includes a ton of optimizations. It works and tests pass, yet, // bugs ARE expected. It will take some time for the compiler to be stable. // Comp // ==== // Compiles a checked Book to C, one source for host and device, or to JS. import * as fs from "node:fs"; import * as Bend from "./bend.ts"; // Types // ===== type Kind = "w32" | "w64" | "box"; type Lay = { ks: Kind[]; arms: Record<Name, Lay[]> | null }; type Val = { ws: string[]; lay: Lay; stat: boolean; rs: (string | null)[] }; type Bind = { val: Val; n: number; A: HTerm }; type Seg = { fid: string; def: Name; ret: Lay; lines: string[]; params: string[]; ks: Kind[]; frame: { pop: number; at: number[] } | null; refs: Set<string>; tab: number; spin: boolean; fork: boolean; native: boolean; head?: string; }; type Spine = { h: HTerm; t: HTerm; all: HTerm[]; args: HTerm[]; live: boolean[]; tld: Bend.TLD | undefined; k: Name | null; xs: HTerm[]; b?: boolean; }; type HTerm = Bend.HTerm; type Name = Bend.Name; type File = ReturnType<typeof file_new>; type Scope = { seg: Seg; fresh: Map<string, number>; spares: Spare[]; uses: Map<Of<"Var">, Bind>; rest: HTerm[]; def: Name; fuel: { n: number }; }; type Spare = { cls: number; name: string; taken: boolean }; type Native = Record<Name, { intr: string; elim?: string[]; cond?: string }>; type Of<K> = Extract<HTerm, { $: K }>; type Row = [HTerm, number, number, number]; type Open = { ps: Of<"Var">[]; b: HTerm }; type Cell = number | boolean; type Intr = { C?: string | string[] | null; JS?: string }; type Dom = [Bend.Quant, Name, HTerm]; type Unit = { name: string; segs: Seg[]; n: number; lent: Set<string>; lends: [string, string][]; clos: Set<string>; emit: () => void }; type Fun = { n: number; h: HTerm | null; live: Dom[]; lays: Lay[]; ret: Lay }; // Constants // ========= // CLO_APPLY and IO~emit are runtime segments (~ keeps files from declaring // them). FOLD_FUEL caps what unfolds add to a segment; a SPIN_FAR-char spin // is a device call (DFAR), and a host call too if it loops on F32 math (SLP // misjudges it); a node past WIDE pads to its size class. const CLO_APPLY = "Clo~apply"; const FOLD_FUEL = 8192; const EXACT = { fround: Math.fround, imul: Math.imul }; const ROWS = new Map<string, (...xs: unknown[]) => Cell>(); const SPIN_FAR = 8192; const USE0 = Bend.Emp<number>(); const W32: Lay = { ks: ["w32"], arms: null }; const BOX: Lay = { ks: ["box"], arms: null }; const W64: Lay = { ks: ["w64"], arms: null }; const WORDS: Record<string, Lay> = Object.setPrototypeOf( { U32: W32, F32: W32, Nat: W64 }, null); const WIDE = 247; const ERRS = ("|*|*|out of memory: run again with a bigger span, as in" + " +RTS --gpu 8GB|a function the device does not hold|a Nat past the" + " largest immediate 2^48-1|*|memory fault (machine stack overflow?)|an" + " array past the deepest block class 31 (depth + log2 words per" + " cell)|a value has more than 2^24-1 live copies: keep fewer alive at" + " once, or build it again for some of them (each build counts its own" + " copies)|expected a Nat host number: an integer from 0 to 2^53") .replaceAll("*", "runtime fail-stop").split("|"); // Operations // ---------- // Array operations have no C text: arr_op lays them out by element. const CMPS = "is_eq:==:=== is_ne:!=:!== is_lt:< is_le:<= is_gt:> is_ge:>="; const AT = "$0[$1 & $0.length - 1]"; const OPERATIONS: Record<string, Intr> = Object.setPrototypeOf({ ...tpl_ops("U32.", "add:+ sub:- and:& or:| xor:^", "U32_BIN($0, $o, $1)", "(($0 $o $1) >>> 0)"), ...tpl_ops("U32.", CMPS, "U32_BIN($0, $o, $1)", "($0 $o $1)"), "U32.mul": { C: "U32_BIN($0, *, $1)", JS: "(Math.imul($0, $1) >>> 0)" }, // C only: intr_of skips an op with no JS, so JS runs Base's "U32.pow": { C: "u32_pow($0, $1)" }, "U32.log2": { C: "(31 - clz((u32)$0 | 1))" }, "U32.popcount": { C: "popcount((u32)$0)" }, "Map.msb.u": { C: "map_msb_u($0, $1)" }, "Map.bit": { C: ["$0", "map_bit(e, $0, $1)"] }, "U32.div": { C: "((u32)($1) == 0 ? 0 : (u64)U32_QUO((u32)($0), (u32)($1)))", JS: "($1 === 0 ? 0 : ($0 / $1) >>> 0)", }, "U32.mod": { C: "((u32)($1) == 0 ? $0 : U32_BIN($0, -," + " U32_QUO((u32)($0), (u32)($1)) * $1))", JS: "($1 === 0 ? $0 : $0 % $1)", }, ...tpl_ops("U32.", "inc:+ shl:<< shr:>>:>>>", "U32_BIN($0, $o, 1)", "(($0 $o 1) >>> 0)"), ...tpl_ops("U32.", "shln:<< shrn:>>:>>>", "($1 >= 32 ? 0 : U32_BIN($0, $o, $1))", "($1 >= 32 ? 0 : ($0 $o $1) >>> 0)"), "U32.not": { C: "((u64)~(u32)($0))", JS: "(~$0 >>> 0)" }, "U32.is_zero": { C: "U32_BIN($0, ==, 0)", JS: "($0 === 0)" }, "U32.cmp": { C: "(U32_BIN($0, >, $1) + U32_BIN($0, >=, $1))", JS: "cmp_new($0, $1)", }, ...tpl_ops("", "U32.to_f32:(u32):>>>0 F32.from_nat::", "f32_rewrap((f32)$o($0))", "Math.fround($0 $o)"), ...tpl_ops("U32.", "to_nat:: from_nat:(u32):>>>0", "((u64)$o($0))", "($0 $o)"), ...tpl_ops("F32.", "add:+ sub:- mul:* div:/", "f32_rewrap(f32_unbox($0) $o f32_unbox($1))", "Math.fround($0 $o $1)"), "F32.neg": { C: "f32_rewrap(-f32_unbox($0))", JS: "(-$0)" }, ...tpl_ops("F32.", CMPS, "((u64)(f32_unbox($0) $o f32_unbox($1)))", "($0 $o $1)"), ...tpl_ops("F32.", "sqrt exp log log2 log10 sin cos tan asin acos atan" + " sinh cosh tanh floor ceil trunc abs:fabs:abs", "f32_rewrap((f32)$o(f32_unbox($0)))", "Math.fround(Math.$o($0))"), ...tpl_ops("F32.", "atan2", "f32_rewrap((f32)$o(f32_unbox($0), f32_unbox($1)))", "Math.fround(Math.$o($0, $1))"), // IEEE's pow(1, y) and pow(-1, inf) are 1; JS's Math.pow says NaN "F32.pow": { C: "f32_rewrap((f32)pow(f32_unbox($0), f32_unbox($1)))", JS: "($0 === 1 || $0 === -1 && Math.abs($1) === Infinity ? 1" + " : Math.fround(Math.pow($0, $1)))", }, "F32.mod": { C: "f32_rewrap((f32)fmod(f32_unbox($0), f32_unbox($1)))", JS: "Math.fround($0 % $1)", }, "F32.to_u32": { C: "f32_to_u32($0)", JS: "($0 >= 1 && $0 < 4294967296 ? Math.floor($0) : 0)", }, "F32.bits": { C: "$0", JS: "f32_bits($0)" }, ...tpl_ops("F32.", "show read", "f32_$o(e, $0)", "f32_$o($0)"), ...tpl_ops("Nat.", "add:$1 double:$0", "nat_chk(e, $0 + $o)", "nat_chk($0 + $o)"), "Nat.mul": { C: "nat_mul(e, $0, $1)", JS: "nat_chk($0 * $1)" }, "Nat.cmp": { C: "(($0 > $1) + ($0 >= $1))", JS: "cmp_new($0, $1)" }, ...tpl_ops("Nat.", "sub", "($0 < $1 ? 0 : $0 - $1)"), ...tpl_ops("Nat.", "is_lt", "($0 < $1)"), ...tpl_ops("Nat.", "min:< max:>", "($0 $o $1 ? $0 : $1)"), "Nat.divmod": { C: ["($1 == 0 ? 0 : $0 / $1)", "($1 == 0 ? $0 : $0 % $1)"], JS: "nat_divmod($0, $1)", }, ...tpl_ops("Bool.", "or:|:|| xor:^:!==", "(($0) $o ($1))", "($0 $o $1)"), "String.append": { JS: "($0 + $1)" }, "String.contains": { JS: "string_contains($0, $1)" }, "String.eq": { JS: "($0 === $1)" }, "String.length": { JS: "[...str_out($0)].length" }, ...Object.fromEntries(Object.entries({ new: "array_new($0, $1, $2)", set: `(${AT} = $2, $0)`, get: `tup_new($0, ${AT})`, get_unchecked: "tup_new($0, $0[$1])", swap: "array_swap($0, $1, $2)", size: "tup_new($0, $0.length)", }).map(([k, JS]) => ["Array." + k, { C: null, JS }])), "Array.clone": { C: ["$0", "blk_copy(e, $0)"], JS: "tup_new($0, $0.slice())", }, ...Object.fromEntries(Object.entries({ add: "($o + $2) >>> 0", min: "Math.min($o, $2)", max: "Math.max($o, $2)", and: "($o & $2) >>> 0", or: "($o | $2) >>> 0", xor: "($o ^ $2) >>> 0", exch: "$2", cmpx: "$o === $2 ? $3 : $o", fadd: "Math.fround($o + $2)", }).map(([k, js]) => ["Array.atomic." + k.replace("cmpx", "cas"), { C: ["$0", "a32_" + k + "(blk_ptr(e.mem, blk_loc(e.mem, $0)," + " blk_at($0, $1, 0)), (u32)$2" + (k === "cmpx" ? ", (u32)$3)" : ")")], JS: `array_swap($0, $1, ${js.replaceAll("$o", AT)})`, }])), }, null); // Optimized // --------- // Per native constructor: builder, field readers, test. The runtime lays // out RUNTIME_ADTS; OWNED are Base names the compiler encodes, Base's alone. const OPTIMIZED: Record<Name, Native> = Object.setPrototypeOf({ Bool: { False: { intr: "false", cond: "!$0" }, True: { intr: "true", cond: "$0" }, }, U32: { U32: { intr: "word_to_u32($0)" } }, F32: { F32: { intr: "f32_from_bits(word_to_u32($0))" } }, Char: { Chr: { intr: "char_new($0)", elim: ["char_code($0)"] } }, Array: { ALeaf: { intr: "[$0]", elim: ["$0[0]"], cond: "$0.length === 1" }, ANode: { intr: "array_node($0, $1)", elim: ["$0.slice(0, $0.length >> 1)", "$0.slice($0.length >> 1)"], cond: "$0.length !== 1", }, }, String: { SNil: { intr: "\"\"", cond: "$0 === \"\"" }, SCon: { intr: "($0 + $1)", elim: ["$0.slice(0, char_len($0))", "$0.slice(char_len($0))"], cond: "$0 !== \"\"", }, }, } satisfies Record<Name, Native>, null); const RUNTIME_ADTS = ["Sigma", "String", "Word.Con", "IO.OP", "Result", "Poll", "Maybe", "Bool", "Unit"]; const OWNED = ["IO", ...RUNTIME_ADTS, "Nat", ...Object.keys(OPTIMIZED)]; // Native // ------ // On Metal, sin, cos and tan are fast:: (same pixels), the rest precise::; // atan2_c99 is libm's +-0 or +-pi at the origin, not NaN; U32_QUO halves // the dividend, as Metal folds one near 2^32 through an f32. const SHIMS = "sqrt exp log log2 log10 sin cos tan pow fmod".split(" ") .map((n) => "#define " + n.padEnd(5) + ("sin cos tan".includes(n) ? " fast::" : " precise::") + n).join("\n") + "\n#define atan2 atan2_c99"; // Caches // ------ export const PROBES: Of<"Var">[] = []; const DUMMY = probe("~"); let FL: File; // Name // ==== function name_clean(k: string): string { return k.replace(/[^A-Za-z0-9_]/g, "_"); } function name_local(sc: Scope, k: Name): string { const base = name_clean(k).replace(/^_+/, ""); const n = sc.fresh.get(base) ?? 0; sc.fresh.set(base, n + 1); const name = `_${base}_${n}`; FL.locals.set(name, k); return name; } function name_id(pre: string, k: string): string { return memo(FL.ids, pre + k, () => { const base = pre + name_clean(k); let id = base; for (let n = 1; FL.taken.has(id); n++) { id = base + "_" + n; } FL.taken.add(id); return id; }); } function cid_mac(k: string): string { return name_id("CID_", k); } // Char // ==== // A non-scalar Char is 0xDC00 and its u32 in three pieces (str_out writes // U+FFFD). The JS runtime copies this function. function char_new(c: number): string { return c < 0xD800 ? String.fromCharCode(c) : c >= 0xE000 && c <= 0x10FFFF ? String.fromCodePoint(c) : String.fromCharCode(0xDC00, c >>> 22, c >>> 11 & 0x7FF, c & 0x7FF); } // Tpl // === function tpl(t: string, xs: string[]): string { return t.replace(/\$(\d)/g, (_, i) => xs[i]); } function nat_peel(t: HTerm, step = (s: HTerm) => s): [HTerm | null, number] { let s = Bend.term_strip(step(t)); let n = 0; for (; s.$ === "Ctr" && s.k === "Succ"; n++) { s = Bend.term_strip(step(s.x.at(-1)!)); } return s.$ === "Lit" ? [null, n + Number(s.v)] : s.$ === "Ctr" ? [null, n] : [s, n]; } // Probe // ===== function probe(k: Name): Of<"Var"> { const p = Bend.Var(k, PROBES.length) as Of<"Var">; PROBES.push(p); return p; } function term_same(a: HTerm, b: HTerm, d = 1 << 29): boolean { const x = Bend.term_strip(a); const y = Bend.term_strip(b) as any; const key = (t: HTerm) => JSON.stringify(Bend.term_lower(t, d), (k, v) => k === "s" ? undefined : v?.$ === "Ann" ? Bend.term_strip(v) : v); if (x === y || x.$ !== y.$) { return x === y; } if (x.$ === "Lam") { const v: HTerm = Bend.Var(x.k, d); return x.k === y.k && x.q?.$ === y.q?.$ && term_same(x.f(v), y.f(v), d + 1); } return x.$ === "App" ? term_same(x.f, y.f, d) && term_same(x.x, y.x, d) : x.$ === "Ctr" ? x.k === y.k && x.x.length === y.x.length && x.x.every((t, i) => term_same(t, y.x[i], d)) : x.$ === "Mat" ? x.k === y.k && term_same(x.h, y.h, d) && term_same(x.m, y.m, d) : key(x) === key(y); } function probe_of(t: HTerm): Of<"Var"> { return PROBES[(t as Of<"Var">).i]; } // Graph // ===== function graph_close<K>(set: Set<K>, edges: K[][]): Set<K> { const out = new Map<K, K[]>(); edges.forEach(([a, b]) => memo(out, a, () => []).push(b)); set.forEach((k) => out.get(k)?.forEach((b) => set.add(b))); return set; } // Term // ==== // A literal is a constant tree, but a Nat past the cap is U32.to_nat of its // word. A spine calls its def on as many live arguments as it has // parameters, else Clo~apply over the outermost live one. function lit_call(s: Of<"Lit">): HTerm | null { return s.k === "Nat" && s.v > Bend.NAT_LITERAL_MAX ? Bend.App(Bend.Ref("U32.to_nat"), Bend.Lit("U32", s.v)) : null; } function term_force(t: HTerm): HTerm { const s = Bend.term_force(t); return s.$ !== "Lit" ? s : memo(FL.steps, s.k + s.v, () => lit_call(s) ?? Bend.lit_step(s)); } function term_strip(t: HTerm): HTerm { return term_force(Bend.term_strip(t)); } function term_open(t: Of<"Lam"> | Of<"Let">): Open { return memo(FL.opens, t, () => { const ps = (t.$ === "Lam" ? [t.k] : t.k).map(probe); return { ps, b: t.$ === "Lam" ? t.f(ps[0]) : t.f(ps) }; }); } function let_open(ps: Of<"Var">[], vs: HTerm[], b: HTerm, q?: Bend.Quant[]): Of<"Let"> { const l = Bend.Let(ps.map((p) => p.k), ps.map(() => 0), vs, () => die("a pre-opened let"), undefined, q) as Of<"Let">; FL.opens.set(l, { ps, b }); return l; } function let_live(t: Of<"Let">): boolean[] { const o = term_open(t); return o.ps.map((p) => rest_use([o.b], p) > 0); } function term_spine(tm: HTerm): Spine { return memo(FL.spines, tm, () => { const apps: Of<"App">[] = []; let h = tm; let c = term_force(tm); while (c.$ === "Ann" || c.$ === "App") { if (c.$ === "App") { apps.unshift(c); h = c.f; } c = term_force(c.$ === "App" ? c.f : c.x); } const tld = c.$ === "Ref" ? tld_of(c.k) : undefined; const T = tld?.$ === "Def" ? tld.T : ty_ann(h); const qs = T === null || apps.length === 0 ? [] : tele_unbind(T).doms; const live = apps.map((_, i) => i >= qs.length || dom_live(qs[i])); const all = apps.map((a) => a.x); const args = all.filter((_, i) => live[i]); const def = c.$ === "Ref" && !intr_of(c.k) && fun_runs(tld) ? c.k : null; const need = def === null ? 0 : fun_of(def).lays.length; const m = { h, t: c, all, args, live, tld, k: null, xs: args }; const a = apps[live.lastIndexOf(true)]; return def !== null && args.length === need ? { ...m, k: def, b: (c as Of<"Ref">).b } : args.length > need && (def !== null || c.$ !== "Ref") ? { ...m, k: CLO_APPLY, xs: [a.f, a.x] } : m; }); } function term_eta(t: HTerm, T: HTerm, n: number): HTerm { return n === 0 ? t : Bend.Ann(Bend.Lam("x", 0, (y: HTe - bend2/docs/film/bitonic.json (12800 bytes)
{ "n": 16, "input": [ 9, 2, 14, 5, 0, 11, 7, 12, 3, 15, 6, 1, 10, 4, 13, 8 ], "output": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ], "note": "stage = (level, step): level k merges runs of 2^k (the bsort call of depth k), step t compares leaves 2^(k-t) apart; dir 0 puts the min at i, dir 1 the max. Level-k blocks alternate: the left child of each bsort sorts asc, the right desc; the root is asc.", "stages": [ { "name": "merge 2 / step 1 (distance 1)", "level": 1, "step": 1, "nodes": [ "TLLL", "TLLR", "TLRL", "TLRR", "TRLL", "TRLR", "TRRL", "TRRR" ], "pairs": [ [ 0, 1, 0, true ], [ 2, 3, 1, false ], [ 4, 5, 0, false ], [ 6, 7, 1, true ], [ 8, 9, 0, false ], [ 10, 11, 1, false ], [ 12, 13, 0, true ], [ 14, 15, 1, false ] ], "after": [ 2, 9, 14, 5, 0, 11, 12, 7, 3, 15, 6, 1, 4, 10, 13, 8 ] }, { "name": "merge 4 / step 1 (distance 2)", "level": 2, "step": 1, "nodes": [ "TLL", "TLR", "TRL", "TRR" ], "pairs": [ [ 0, 2, 0, false ], [ 1, 3, 0, true ], [ 4, 6, 1, true ], [ 5, 7, 1, false ], [ 8, 10, 0, false ], [ 9, 11, 0, true ], [ 12, 14, 1, true ], [ 13, 15, 1, false ] ], "after": [ 2, 5, 14, 9, 12, 11, 0, 7, 3, 1, 6, 15, 13, 10, 4, 8 ] }, { "name": "merge 4 / step 2 (distance 1)", "level": 2, "step": 2, "nodes": [ "TLL", "TLR", "TRL", "TRR" ], "pairs": [ [ 0, 1, 0, false ], [ 2, 3, 0, true ], [ 4, 5, 1, false ], [ 6, 7, 1, true ], [ 8, 9, 0, true ], [ 10, 11, 0, false ], [ 12, 13, 1, false ], [ 14, 15, 1, true ] ], "after": [ 2, 5, 9, 14, 12, 11, 7, 0, 1, 3, 6, 15, 13, 10, 8, 4 ] }, { "name": "merge 8 / step 1 (distance 4)", "level": 3, "step": 1, "nodes": [ "TL", "TR" ], "pairs": [ [ 0, 4, 0, false ], [ 1, 5, 0, false ], [ 2, 6, 0, true ], [ 3, 7, 0, true ], [ 8, 12, 1, true ], [ 9, 13, 1, true ], [ 10, 14, 1, true ], [ 11, 15, 1, false ] ], "after": [ 2, 5, 7, 0, 12, 11, 9, 14, 13, 10, 8, 15, 1, 3, 6, 4 ] }, { "name": "merge 8 / step 2 (distance 2)", "level": 3, "step": 2, "nodes": [ "TL", "TR" ], "pairs": [ [ 0, 2, 0, false ], [ 1, 3, 0, true ], [ 4, 6, 0, true ], [ 5, 7, 0, false ], [ 8, 10, 1, false ], [ 9, 11, 1, true ], [ 12, 14, 1, true ], [ 13, 15, 1, true ] ], "after": [ 2, 0, 7, 5, 9, 11, 12, 14, 13, 15, 8, 10, 6, 4, 1, 3 ] }, { "name": "merge 8 / step 3 (distance 1)", "level": 3, "step": 3, "nodes": [ "TL", "TR" ], "pairs": [ [ 0, 1, 0, true ], [ 2, 3, 0, true ], [ 4, 5, 0, false ], [ 6, 7, 0, false ], [ 8, 9, 1, true ], [ 10, 11, 1, true ], [ 12, 13, 1, false ], [ 14, 15, 1, true ] ], "after": [ 0, 2, 5, 7, 9, 11, 12, 14, 15, 13, 10, 8, 6, 4, 3, 1 ] }, { "name": "merge 16 / step 1 (distance 8)", "level": 4, "step": 1, "nodes": [ "T" ], "pairs": [ [ 0, 8, 0, false ], [ 1, 9, 0, false ], [ 2, 10, 0, false ], [ 3, 11, 0, false ], [ 4, 12, 0, true ], [ 5, 13, 0, true ], [ 6, 14, 0, true ], [ 7, 15, 0, true ] ], "after": [ 0, 2, 5, 7, 6, 4, 3, 1, 15, 13, 10, 8, 9, 11, 12, 14 ] }, { "name": "merge 16 / step 2 (distance 4)", "level": 4, "step": 2, "nodes": [ "T" ], "pairs": [ [ 0, 4, 0, false ], [ 1, 5, 0, false ], [ 2, 6, 0, true ], [ 3, 7, 0, true ], [ 8, 12, 0, true ], [ 9, 13, 0, true ], [ 10, 14, 0, false ], [ 11, 15, 0, false ] ], "after": [ 0, 2, 3, 1, 6, 4, 5, 7, 9, 11, 10, 8, 15, 13, 12, 14 ] }, { "name": "merge 16 / step 3 (distance 2)", "level": 4, "step": 3, "nodes": [ "T" ], "pairs": [ [ 0, 2, 0, false ], [ 1, 3, 0, true ], [ 4, 6, 0, true ], [ 5, 7, 0, false ], [ 8, 10, 0, false ], [ 9, 11, 0, true ], [ 12, 14, 0, true ], [ 13, 15, 0, false ] ], "after": [ 0, 1, 3, 2, 5, 4, 6, 7, 9, 8, 10, 11, 12, 13, 15, 14 ] }, { "name": "merge 16 / step 4 (distance 1)", "level": 4, "step": 4, "nodes": [ "T" ], "pairs": [ [ 0, 1, 0, false ], [ 2, 3, 0, true ], [ 4, 5, 0, true ], [ 6, 7, 0, false ], [ 8, 9, 0, true ], [ 10, 11, 0, false ], [ 12, 13, 0, false ], [ 14, 15, 0, true ] ], "after": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] } ], "tree": { "id": "T", "depth": 4, "dir": "asc", "x": 0, "leaves": [ 0, 16 ], "kids": [ { "id": "TL", "depth": 3, "dir": "asc", "x": 1, "leaves": [ 0, 8 ], "kids": [ { "id": "TLL", "depth": 2, "dir": "asc", "x": 3, "leaves": [ 0, 4 ], "kids": [ { "id": "TLLL", "depth": 1, "dir": "asc", "x": 7, "leaves": [ 0, 2 ], "kids": [ { "id": "TLLLL", "depth": 0, "dir": "asc", "x": 15, "leaves": [ 0, 1 ], "kids": [] }, { "id": "TLLLR", "depth": 0, "dir": "desc", "x": 14, "leaves": [ 1, 2 ], "kids": [] } ] }, { "id": "TLLR", "depth": 1, "dir": "desc", "x": 6, "leaves": [ 2, 4 ], "kids": [ { "id": "TLLRL", "depth": 0, "dir": "asc", "x": 13, "leaves": [ 2, 3 ], "kids": [] }, { "id": "TLLRR", "depth": 0, "dir": "desc", "x": 12, "leaves": [ 3, 4 ], "kids": [] } ] } ] }, { "id": "TLR", "depth": 2, "dir": "desc", "x": 2, "leaves": [ 4, 8 ], "kids": [ { "id": "TLRL", "depth": 1, "dir": "asc", "x": 5, "leaves": [ 4, 6 ], "kids": [ { "id": "TLRLL", "depth": 0, "dir": "asc", "x": 11, "leaves": [ 4, 5 ], "kids": [] }, { "id": "TLRLR", "depth": 0, "dir": "desc", "x": 10, "leaves": [ 5, 6 ], "kids": [] } ] }, { "id": "TLRR", "depth": 1, "dir": "desc", "x": 4, "leaves": [ 6, 8 ], "kids": [ { "id": "TLRRL", "depth": 0, "dir": "asc", "x": 9, "leaves": [ 6, 7 ], "kids": [] }, { "id": "TLRRR", "depth": 0, "dir": "desc", "x": 8, "leaves": [ 7, 8 ], "kids": [] } ] } ] } ] }, { "id": "TR", "depth": 3, "dir": "desc", "x": 0, "leaves": [ 8, 16 ], "kids": [ { "id": "TRL", "depth": 2, "dir": "asc", "x": 1, "leaves": [ 8, 12 ], "kids": [ { "id": "TRLL", "depth": 1, "dir": "asc", "x": 3, "leaves": [ 8, 10 ], "kids": [ { "id": "TRLLL", "depth": 0, "dir": "asc", "x": 7, "leaves": [ 8, 9 ], "kids": [] }, { "id": "TRLLR", "depth": 0, "dir": "desc", "x": 6, "leaves": [ 9, 10 ], "kids": [] } ] }, { "id": "TRLR", "depth": 1, "dir": "desc", "x": 2, "leaves": [ 10, 12 ], "kids": [ { "id": "TRLRL", "depth": 0, "dir": "asc", "x": 5, "leaves": [ 10, 11 ], "kids": [] }, { "id": "TRLRR", "depth": 0, "dir": "desc", "x": 4, "leaves": [ 11, 12 ], "kids": [] } ] } ] }, { "id": "TRR", "depth": 2, "dir": "desc", "x": 0, "leaves": [ 12, 16 ], "kids": [ { "id": "TRRL", "depth": 1, "dir": "asc", "x": 1, "leaves": [ 12, 14 ], "kids": [ { "id": "TRRLL", "depth": 0, "dir": "asc", "x": 3, "leaves": [ 12, 13 ], "kids": [] }, { "id": "TRRLR", "depth": 0, "dir": "desc", "x": 2, "leaves": [ 13, 14 ], "kids": [] } ] }, { "id": "TRRR", "depth": 1, "dir": "desc", "x": 0, "leaves": [ 14, 16 ], "kids": [ { "id": "TRRRL", "depth": 0, "dir": "asc", "x": 1, "leaves": [ 14, 15 ], "kids": [] }, { "id": "TRRRR", "depth": 0, "dir": "desc", "x": 0, "leaves": [ 15, 16 ], "kids": [] } ] } ] } ] } ] } } - bend2/docs/film/film.ts (137451 bytes)
import * as fs from "node:fs"; import * as path from "node:path"; // The Bend film, cut to "A Cruel Angel's Thesis": media/kind_devil_theorem.mp4. // bun film.ts part i n | join | sheet t0 t1 step // The song is not in the repo ($NERV_SONG); the sprites, the parts and the // sheets go to .tmp/film. const DIR = import.meta.dir; const TMP = process.env.NERV_TMP ?? path.join(DIR, "../../../.tmp/film"); const SONG = process.env.NERV_SONG ?? path.join(TMP, "song.m4a"); const OUT = process.env.NERV_OUT ?? path.join(TMP, "bend.mp4"); const S = Number(process.env.NERV_SCALE ?? 1); const W = Math.round(1440 * S); const H = Math.round(1080 * S); const FPS = 24; const END = 89.6; const PARTS = Number(process.env.NERV_PARTS ?? 64); // Math // ==== function clamp(x: number, a = 0, b = 1): number { return x < a ? a : x > b ? b : x; } // The progress of t through [a, b], clamped to [0, 1]. function prog(t: number, a: number, b: number): number { return clamp((t - a) / (b - a)); } function smooth(x: number): number { x = clamp(x); return x * x * (3 - 2 * x); } function lerp(a: number, b: number, x: number): number { return a + (b - a) * x; } // A deterministic hash of an integer (and a seed) into [0, 1). function hash(i: number, s = 0): number { let h = Math.imul(i ^ Math.imul(s + 0x9e3779b9, 0x85ebca6b), 0xc2b2ae35); h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d); h = Math.imul(h ^ (h >>> 12), 0x297a2d39); return ((h ^ (h >>> 15)) >>> 0) / 4294967296; } // Value noise with fractal octaves, in [0, 1). function noise(x: number, y: number, s: number): number { const xi = Math.floor(x), yi = Math.floor(y); const u = smooth(x - xi), v = smooth(y - yi); const k = (a: number, b: number) => hash(a * 7919 + b * 104729, s); return lerp(lerp(k(xi, yi), k(xi + 1, yi), u), lerp(k(xi, yi + 1), k(xi + 1, yi + 1), u), v); } function fbm(x: number, y: number, s: number): number { let sum = 0, amp = 0.5; for (let o = 0; o < 5; ++o) { sum += amp * noise(x, y, s + o); x *= 2.03; y *= 2.03; amp *= 0.5; } return sum / 0.97; } // Colors // ====== // Sampled from the source film. type Col = [number, number, number]; const hex = (h: number): Col => [(h >> 16) / 255, ((h >> 8) & 255) / 255, (h & 255) / 255]; const BG = hex(0x141d18); const TXT = hex(0xd0cfc2); // captions const STATE = hex(0xc8cc98); // statements const DIM = hex(0x8a9285); // credits const LINE = hex(0xaeaf9e); // diagram lines const YEL = hex(0xe0d060); const CYAN = hex(0xa7b7d4); const ORANGE = hex(0xd07040); const OCHRE = hex(0xb0a67f); const F_RED = hex(0x80161a); const F_OCH = hex(0x3d2d10); const F_GRN = hex(0x1c3318); const F_BLU = hex(0x293976); const RING = hex(0x2050d0); const REDL = hex(0xd04a40); // red labels const GRNL = hex(0x7fbf6a); // green labels const GOLD = hex(0xe8b040); const RED = hex(0xd53843); const GREEN = hex(0x4c9a3c); const CREAM = hex(0xdbc7af); const WHITE: Col = [1, 1, 1]; const BLACK: Col = [0, 0, 0]; // Canvas // ====== // The frame, in RGB floats; every shape paints over it with an alpha. const buf = new Float32Array(W * H * 3); // The film base: BG, mottled by a slow noise, drawn once. const base = new Float32Array(W * H * 3); for (let y = 0; y < H; ++y) { for (let x = 0; x < W; ++x) { const m = 0.8 + 0.4 * fbm(x / (260 * S), y / (260 * S), 3); const k = (y * W + x) * 3; base[k] = BG[0] * m; base[k + 1] = BG[1] * m; base[k + 2] = BG[2] * m; } } function paint(i: number, c: Col, a: number): void { const k = i * 3; buf[k] += (c[0] - buf[k]) * a; buf[k + 1] += (c[1] - buf[k + 1]) * a; buf[k + 2] += (c[2] - buf[k + 2]) * a; } // Fills the picture. function fill(c: Col, a = 1): void { for (let i = 0; i < W * H; ++i) paint(i, c, a); } function rect(x: number, y: number, w: number, h: number, c: Col, a = 1): void { const x0 = Math.max(0, Math.round(x * S)), x1 = Math.min(W, Math.round((x + w) * S)); const y0 = Math.max(0, Math.round(y * S)), y1 = Math.min(H, Math.round((y + h) * S)); for (let py = y0; py < y1; ++py) { for (let px = x0; px < x1; ++px) paint(py * W + px, c, a); } } // A segment of width w, antialiased by its distance to each pixel. function line(x0: number, y0: number, x1: number, y1: number, w: number, c: Col, a = 1): void { if (a <= 0) return; x0 *= S; y0 *= S; x1 *= S; y1 *= S; w *= S; const r = w / 2 + 1; const bx = Math.max(0, Math.floor(Math.min(x0, x1) - r)), ex = Math.min(W - 1, Math.ceil(Math.max(x0, x1) + r)); const by = Math.max(0, Math.floor(Math.min(y0, y1) - r)), ey = Math.min(H - 1, Math.ceil(Math.max(y0, y1) + r)); const dx = x1 - x0, dy = y1 - y0, ll = dx * dx + dy * dy || 1e-9; for (let py = by; py <= ey; ++py) { for (let px = bx; px <= ex; ++px) { const qx = px + 0.5 - x0, qy = py + 0.5 - y0; const h = clamp((qx * dx + qy * dy) / ll); const cx = qx - h * dx, cy = qy - h * dy; const cv = w / 2 + 0.5 - Math.sqrt(cx * cx + cy * cy); if (cv > 0) paint(py * W + px, c, a * Math.min(1, cv)); } } } // A circle of radius r; with f < 1, only the arc from the top, clockwise, to // the fraction f of a turn. function ring(cx: number, cy: number, r: number, w: number, c: Col, a = 1, f = 1): void { if (a <= 0 || f <= 0) return; cx *= S; cy *= S; r *= S; w *= S; const e = r + w / 2 + 1; const bx = Math.max(CLIP0, Math.floor(cx - e)), ex = Math.min(W - 1, CLIP1 - 1, Math.ceil(cx + e)); const by = Math.max(0, Math.floor(cy - e)), ey = Math.min(H - 1, Math.ceil(cy + e)); for (let py = by; py <= ey; ++py) { for (let px = bx; px <= ex; ++px) { const dx = px + 0.5 - cx, dy = py + 0.5 - cy; const cv = w / 2 + 0.5 - Math.abs(Math.sqrt(dx * dx + dy * dy) - r); if (cv <= 0) continue; if (f < 1 && (Math.atan2(dx, -dy) / (2 * Math.PI) + 1) % 1 > f) continue; paint(py * W + px, c, a * Math.min(1, cv)); } } } function disc(cx: number, cy: number, r: number, c: Col, a = 1): void { if (a <= 0) return; cx *= S; cy *= S; r *= S; const bx = Math.max(CLIP0, Math.floor(cx - r - 1)), ex = Math.min(W - 1, CLIP1 - 1, Math.ceil(cx + r + 1)); const by = Math.max(0, Math.floor(cy - r - 1)), ey = Math.min(H - 1, Math.ceil(cy + r + 1)); for (let py = by; py <= ey; ++py) { for (let px = bx; px <= ex; ++px) { const dx = px + 0.5 - cx, dy = py + 0.5 - cy; const cv = r + 0.5 - Math.sqrt(dx * dx + dy * dy); if (cv > 0) paint(py * W + px, c, a * Math.min(1, cv)); } } } // A filled triangle, by the sign of its three edges. function tri(ax: number, ay: number, bx: number, by: number, cx: number, cy: number, c: Col, a = 1): void { const xs = [ax, bx, cx].map(v => v * S), ys = [ay, by, cy].map(v => v * S); const x0 = Math.max(0, Math.floor(Math.min(...xs))), x1 = Math.min(W - 1, Math.ceil(Math.max(...xs))); const y0 = Math.max(0, Math.floor(Math.min(...ys))), y1 = Math.min(H - 1, Math.ceil(Math.max(...ys))); const side = (i: number, j: number, px: number, py: number) => (xs[j] - xs[i]) * (py - ys[i]) - (ys[j] - ys[i]) * (px - xs[i]); for (let py = y0; py <= y1; ++py) { for (let px = x0; px <= x1; ++px) { const s0 = side(0, 1, px + 0.5, py + 0.5), s1 = side(1, 2, px + 0.5, py + 0.5), s2 = side(2, 0, px + 0.5, py + 0.5); if ((s0 >= 0 && s1 >= 0 && s2 >= 0) || (s0 <= 0 && s1 <= 0 && s2 <= 0)) paint(py * W + px, c, a); } } } type Pt = [number, number]; // A polyline, drawn up to the fraction f of its length (the pen). function poly(pts: Pt[], w: number, c: Col, a = 1, f = 1): void { if (a <= 0 || f <= 0 || pts.length < 2) return; let len = 0; for (let i = 1; i < pts.length; ++i) len += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]); let left = len * clamp(f); for (let i = 1; i < pts.length && left > 0; ++i) { const [x0, y0] = pts[i - 1], [x1, y1] = pts[i]; const d = Math.hypot(x1 - x0, y1 - y0), k = Math.min(1, left / (d || 1e-9)); line(x0, y0, x0 + (x1 - x0) * k, y0 + (y1 - y0) * k, w, c, a); left -= d; } } // A cubic Bezier as n points. function bez(p0: Pt, p1: Pt, p2: Pt, p3: Pt, n = 24): Pt[] { const out: Pt[] = []; for (let i = 0; i <= n; ++i) { const t = i / n, u = 1 - t; out.push([u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0], u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]]); } return out; } // A triangle outline of circumradius r, its apex toward angle g (radians, // 0 = up), drawn up to the fraction f of its perimeter. function tri_o(cx: number, cy: number, r: number, g: number, w: number, c: Col, a = 1, f = 1): Pt[] { const v: Pt[] = [0, 1, 2].map(k => [cx + r * Math.sin(g + k * 2 * Math.PI / 3), cy - r * Math.cos(g + k * 2 * Math.PI / 3)] as Pt); poly([v[0], v[1], v[2], v[0]], w, c, a, f); return v; } // A dashed segment: n dashes, each filling the fraction on of its slot. function dash(x0: number, y0: number, x1: number, y1: number, w: number, c: Col, a = 1, n = 12, on = 0.55): void { for (let i = 0; i < n; ++i) { const u0 = i / n, u1 = (i + on) / n; line(lerp(x0, x1, u0), lerp(y0, y1, u0), lerp(x0, x1, u1), lerp(y0, y1, u1), w, c, a); } } // A noise field (clouds): drawn at 1/8 size, stretched with bilinear taps. function clouds(t: number, c0: Col, c1: Col, a: number, zoom: number, seed: number): void { const gw = Math.ceil(W / 8) + 2, gh = Math.ceil(H / 8) + 2; const g = new Float32Array(gw * gh); for (let y = 0; y < gh; ++y) { for (let x = 0; x < gw; ++x) { const u = (x * 8 / S) / zoom, v = (y * 8 / S) / zoom; g[y * gw + x] = smooth(fbm(u + t * 0.9, v + t * 0.25, seed) * 1.3 - 0.15); } } for (let py = 0; py < H; ++py) { const gy = py / 8, y0 = Math.floor(gy), fy = gy - y0; for (let px = 0; px < W; ++px) { const gx = px / 8, x0 = Math.floor(gx), fx = gx - x0, k = y0 * gw + x0; const m = lerp(lerp(g[k], g[k + 1], fx), lerp(g[k + gw], g[k + gw + 1], fx), fy); const i = (py * W + px) * 3; for (let ch = 0; ch < 3; ++ch) buf[i + ch] += (lerp(c0[ch], c1[ch], m) - buf[i + ch]) * a; } } } // Sprites // ======= // Every text is a white typst sprite, registered at load and drawn by alpha. type Sprite = { w: number; h: number; a: Uint8Array }; const MARKUP: string[] = []; const SPRITES: Sprite[] = []; function str(s: string): string { return JSON.stringify(s); } function sprite(markup: string): number { MARKUP.push(markup); return MARKUP.length - 1; } // Loads every sprite: one typst run, one ffmpeg decode per page, cached. function sprite_load(): void { fs.mkdirSync(TMP, { recursive: true }); const src = `#set page(width: auto, height: auto, margin: 40pt, fill: none) #set text(fill: white, top-edge: "bounds", bottom-edge: "bounds") ` + MARKUP.join("\n#pagebreak()\n") + "\n"; const dir = path.join(TMP, `spr-${S}`); const stamp = path.join(dir, "src.typ"); if (!fs.existsSync(stamp) || fs.readFileSync(stamp, "utf8") !== src) { fs.mkdirSync(dir, { recursive: true }); const tmp = path.join(dir, `next-${process.pid}.typ`); fs.writeFileSync(tmp, src); run(["typst", "compile", "--ppi", String(72 * S), tmp, path.join(dir, "{0p}.png")]); const n = String(MARKUP.length).length; for (let i = 0; i < MARKUP.length; ++i) { const png = path.join(dir, String(i + 1).padStart(n, "0") + ".png"); const rgba = run(["ffmpeg", "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgba", "-"]); const head = fs.readFileSync(png); const pw = head.readUInt32BE(16), ph = head.readUInt32BE(20); // Crops the page to its ink, plus 2 px: the wide page margin keeps // every ascender and descender, and the crop keeps anchors exact. let x0 = pw, y0 = ph, x1 = 0, y1 = 0; for (let j = 0; j < pw * ph; ++j) { if (rgba[j * 4 + 3] === 0) continue; const x = j % pw, y = (j - x) / pw; x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); } x0 = Math.max(0, x0 - 2); y0 = Math.max(0, y0 - 2); x1 = Math.min(pw - 1, x1 + 2); y1 = Math.min(ph - 1, y1 + 2); const w = x1 - x0 + 1, h = y1 - y0 + 1; const a = new Uint8Array(w * h); for (let y = 0; y < h; ++y) for (let x = 0; x < w; ++x) a[y * w + x] = rgba[((y + y0) * pw + x + x0) * 4 + 3]; fs.writeFileSync(path.join(dir, `${i}.a`), Buffer.concat([Buffer.from(new Uint32Array([w, h]).buffer), a])); } fs.renameSync(tmp, stamp); } for (let i = 0; i < MARKUP.length; ++i) { const b = fs.readFileSync(path.join(dir, `${i}.a`)); const w = b.readUInt32LE(0), h = b.readUInt32LE(4); SPRITES.push({ w, h, a: new Uint8Array(b.buffer, b.byteOffset + 8, w * h) }); } } type Blit = { c?: Col; a?: number; ax?: number; ay?: number; z?: number; show?: number }; // Draws a sprite at (x, y): ax/ay anchor it (0 = left/top, 1 = right/bottom), // z scales it, and show reveals its left fraction (the typewriter). function blit(id: number, x: number, y: number, o: Blit = {}): void { const sp = SPRITES[id], c = o.c ?? CREAM, al = o.a ?? 1, z = o.z ?? 1; if (al <= 0) return; const w = sp.w * z, h = sp.h * z; const x0 = x * S - (o.ax ?? 0) * w, y0 = y * S - (o.ay ?? 0) * h; const cut = x0 + w * clamp(o.show ?? 1); const bx = Math.max(0, Math.floor(x0)), ex = Math.min(W, Math.ceil(Math.min(x0 + w, cut))); const by = Math.max(0, Math.floor(y0)), ey = Math.min(H, Math.ceil(y0 + h)); for (let py = by; py < ey; ++py) { const sy = (py + 0.5 - y0) / z - 0.5; const iy = Math.max(0, Math.min(sp.h - 1, Math.round(sy))); for (let px = bx; px < ex; ++px) { let v: number; if (z === 1) { const ix = px - Math.round(x0); const jy = py - Math.round(y0); v = ix >= 0 && ix < sp.w && jy >= 0 && jy < sp.h ? sp.a[jy * sp.w + ix] : 0; } else { const sx = (px + 0.5 - x0) / z - 0.5; const x1 = Math.floor(sx), y1 = Math.floor(sy), fx = sx - x1, fy = sy - y1; const at = (i: number, j: number) => i >= 0 && i < sp.w && j >= 0 && j < sp.h ? sp.a[j * sp.w + i] : 0; v = lerp(lerp(at(x1, y1), at(x1 + 1, y1), fx), lerp(at(x1, y1 + 1), at(x1 + 1, y1 + 1), fx), fy); void iy; } if (v > 0) paint(py * W + px, c, al * v / 255); } } } // Texts // ===== // The three type systems of the opening: the // CRT captions in a slim mono, wide tracked (sizes are pixels at 1080, // where 1 pt is 1 px); the flash cards in a condensed bold grotesque, ALL // CAPS, stretched to 82% of the picture's width; the staff card in a heavy // Mincho. function mono(s: string, size = 64, track = 0.14): number { return sprite(`#text(font: "Andale Mono", size: ${size}pt, tracking: ${track}em, ${str(s)})`); } // A flash card: cap height cap (px), the width fit to fit (px), clamped to // an x-scale of 55-110%. With top, a small bold - bend2/docs/film/logo.json (7358 bytes)
{ "box": [ 1000, 1000 ], "ink": "#000000", "paper": "#ECE8E7", "accent": "#D8030B", "width": 20, "source": "https://web.archive.org/web/20240516025206id_/https://higherorderco.com/logo.svg (embedded 1214x933 PNG); map x'=0.94899*x-81.257, y'=0.94899*y+63.464", "bezier": "cubic chain: pts = [P0, C1, C2, P1, C1, C2, P2, ...]", "nodes": [ { "id": "A", "kind": "tri", "fill": false, "pts": [ [ 206, 280 ], [ 333, 359 ], [ 199, 436 ] ], "ports": { "main": [ 333, 359 ], "aux": [ [ 199, 316 ], [ 196, 368 ] ] } }, { "id": "B", "kind": "tri", "fill": true, "pts": [ [ 697, 655 ], [ 810, 593 ], [ 799, 752 ] ], "ports": { "main": [ 697, 655 ], "aux": [ [ 812, 642 ], [ 806, 686 ] ] } }, { "id": "dot", "kind": "circle", "cx": 212, "cy": 225, "r": 23, "fill": true }, { "id": "ring", "kind": "circle", "cx": 798, "cy": 800, "r": 15, "fill": false } ], "wires": [ { "id": "trunk", "role": "A.main <-> B.main: the active pair", "taper": null, "curve": "bezier", "width": 20, "pts": [ [ 333, 359 ], [ 341.0, 363.2 ], [ 365.8, 374.0 ], [ 381, 384 ], [ 396.2, 394.0 ], [ 409.7, 404.8 ], [ 424, 419 ], [ 438.3, 433.2 ], [ 452.5, 451.7 ], [ 467, 469 ], [ 481.5, 486.3 ], [ 496.2, 505.5 ], [ 511, 523 ], [ 525.8, 540.5 ], [ 540.8, 558.5 ], [ 556, 574 ], [ 571.2, 589.5 ], [ 587.0, 603.3 ], [ 602, 616 ], [ 617.0, 628.7 ], [ 630.2, 643.5 ], [ 646, 650 ], [ 661.8, 656.5 ], [ 688.5, 654.2 ], [ 697, 655 ] ] }, { "id": "lobe_left", "role": "A.aux2 -> left lobe; free end dips under the trunk", "taper": "end", "curve": "bezier", "width": 20, "pts": [ [ 196, 368 ], [ 191.0, 373.2 ], [ 176.3, 386.8 ], [ 166, 399 ], [ 155.7, 411.2 ], [ 142.2, 425.0 ], [ 134, 441 ], [ 125.8, 457.0 ], [ 119.2, 475.3 ], [ 117, 495 ], [ 114.8, 514.7 ], [ 115.7, 538.5 ], [ 121, 559 ], [ 126.3, 579.5 ], [ 136.8, 601.2 ], [ 149, 618 ], [ 161.2, 634.8 ], [ 176.3, 651.0 ], [ 194, 660 ], [ 211.7, 669.0 ], [ 235.0, 671.8 ], [ 255, 672 ], [ 275.0, 672.2 ], [ 295.0, 668.3 ], [ 314, 661 ], [ 333.0, 653.7 ], [ 351.7, 640.2 ], [ 369, 628 ], [ 386.3, 615.8 ], [ 403.7, 600.8 ], [ 418, 588 ], [ 432.3, 575.2 ], [ 448.8, 557.2 ], [ 455, 551 ] ] }, { "id": "lobe_right", "role": "right lobe -> B.aux1; resumes past the trunk", "taper": "start", "curve": "bezier", "width": 20, "pts": [ [ 555, 468 ], [ 562.3, 460.2 ], [ 583.2, 435.2 ], [ 599, 421 ], [ 614.8, 406.8 ], [ 631.7, 392.8 ], [ 650, 383 ], [ 668.3, 373.2 ], [ 689.8, 366.3 ], [ 709, 362 ], [ 728.2, 357.7 ], [ 747.5, 355.0 ], [ 765, 357 ], [ 782.5, 359.0 ], [ 799.7, 364.2 ], [ 814, 374 ], [ 828.3, 383.8 ], [ 841.0, 399.7 ], [ 851, 416 ], [ 861.0, 432.3 ], [ 870.2, 452.5 ], [ 874, 472 ], [ 877.8, 491.5 ], [ 876.7, 513.0 ], [ 874, 533 ], [ 871.3, 553.0 ], [ 868.3, 573.8 ], [ 858, 592 ], [ 847.7, 610.2 ], [ 819.7, 633.7 ], [ 812, 642 ] ] }, { "id": "curl_top", "role": "A.aux1 -> dot", "taper": null, "curve": "bezier", "width": 20, "pts": [ [ 198, 316 ], [ 191.3, 314.5 ], [ 170.3, 311.0 ], [ 158, 307 ], [ 145.7, 303.0 ], [ 131.5, 301.7 ], [ 124, 292 ], [ 116.5, 282.3 ], [ 113.8, 262.8 ], [ 113, 249 ], [ 112.2, 235.2 ], [ 115.0, 220.8 ], [ 119, 209 ], [ 123.0, 197.2 ], [ 128.2, 186.0 ], [ 137, 178 ], [ 145.8, 170.0 ], [ 160.2, 163.0 ], [ 172, 161 ], [ 183.8, 159.0 ], [ 198.8, 161.5 ], [ 208, 166 ], [ 217.2, 170.5 ], [ 224.8, 180.5 ], [ 227, 188 ], [ 229.2, 195.5 ], [ 223.5, 204.8 ], [ 221, 211 ], [ 218.5, 217.2 ], [ 213.5, 222.7 ], [ 212, 225 ] ] }, { "id": "curl_bottom", "role": "B.aux2 -> ring", "taper": null, "curve": "bezier", "width": 20, "pts": [ [ 806, 686 ], [ 812.2, 687.8 ], [ 832.2, 691.2 ], [ 843, 697 ], [ 853.8, 702.8 ], [ 863.5, 710.3 ], [ 871, 721 ], [ 878.5, 731.7 ], [ 886.5, 747.3 ], [ 888, 761 ], [ 889.5, 774.7 ], [ 884.8, 791.2 ], [ 880, 803 ], [ 875.2, 814.8 ], [ 868.8, 826.3 ], [ 859, 832 ], [ 849.2, 837.7 ], [ 832.0, 839.5 ], [ 821, 837 ], [ 810.0, 834.5 ], [ 799.7, 824.0 ], [ 793, 817 ], [ 786.3, 810.0 ], [ 780.7, 800.3 ], [ 781, 795 ], [ 781.3, 789.7 ], [ 792.7, 786.7 ], [ 795, 785 ] ] } ], "text": [ { "str": "HigherOrder", "weight": "bold", "font": "Helvetica Neue (or Arial) grotesque, black" }, { "str": "Company", "weight": "regular", "note": "no space; set right below the mark in hoc-logo.png" } ] } - bend2/docs/film/net.json (9998 bytes)
{"steps":[{"nodes":[{"id":0,"kind":"root","label":0,"x":0.5161,"y":0.224,"angle":1.7354,"flip":false},{"id":1,"kind":"app","label":0,"x":0.4926,"y":0.3655,"angle":2.7664,"flip":true},{"id":2,"kind":"lam","label":0,"x":0.3451,"y":0.4236,"angle":-0.3752,"flip":true},{"id":3,"kind":"lam","label":0,"x":0.2146,"y":0.5135,"angle":-0.6032,"flip":true},{"id":4,"kind":"app","label":0,"x":0.1479,"y":0.5759,"angle":-1.0396,"flip":true},{"id":5,"kind":"app","label":0,"x":0.1,"y":0.4976,"angle":-0.3927,"flip":true},{"id":6,"kind":"dup","label":1,"x":0.2241,"y":0.4462,"angle":-0.1846,"flip":false},{"id":7,"kind":"lam","label":0,"x":0.6492,"y":0.4104,"angle":-2.8624,"flip":false},{"id":8,"kind":"lam","label":0,"x":0.7818,"y":0.5063,"angle":-2.5154,"flip":false},{"id":9,"kind":"app","label":0,"x":0.845,"y":0.5803,"angle":-2.0095,"flip":false},{"id":10,"kind":"app","label":0,"x":0.9,"y":0.5011,"angle":-2.6946,"flip":false},{"id":11,"kind":"dup","label":2,"x":0.7811,"y":0.4441,"angle":-2.8914,"flip":true}],"wires":[{"a":[0,0],"b":[1,2]},{"a":[1,0],"b":[2,0]},{"a":[1,1],"b":[7,0]},{"a":[2,1],"b":[6,0]},{"a":[2,2],"b":[3,0]},{"a":[3,1],"b":[5,1]},{"a":[3,2],"b":[4,2]},{"a":[4,0],"b":[6,1]},{"a":[4,1],"b":[5,2]},{"a":[5,0],"b":[6,2]},{"a":[7,1],"b":[11,0]},{"a":[7,2],"b":[8,0]},{"a":[8,1],"b":[10,1]},{"a":[8,2],"b":[9,2]},{"a":[9,0],"b":[11,1]},{"a":[9,1],"b":[10,2]},{"a":[10,0],"b":[11,2]}],"active":[[1,2]],"rules":["beta"]},{"nodes":[{"id":0,"kind":"root","label":0,"x":0.5161,"y":0.224,"angle":2.5147,"flip":false},{"id":3,"kind":"lam","label":0,"x":0.3993,"y":0.3086,"angle":-0.6269,"flip":true},{"id":4,"kind":"app","label":0,"x":0.3675,"y":0.4216,"angle":1.1817,"flip":false},{"id":5,"kind":"app","label":0,"x":0.2954,"y":0.3975,"angle":0.7969,"flip":true},{"id":6,"kind":"dup","label":1,"x":0.4026,"y":0.5072,"angle":0.657,"flip":true},{"id":7,"kind":"lam","label":0,"x":0.5277,"y":0.6037,"angle":-2.4845,"flip":false},{"id":8,"kind":"lam","label":0,"x":0.655,"y":0.6887,"angle":-2.5529,"flip":false},{"id":9,"kind":"app","label":0,"x":0.7317,"y":0.7497,"angle":-2.1869,"flip":false},{"id":10,"kind":"app","label":0,"x":0.7749,"y":0.6664,"angle":-2.8576,"flip":false},{"id":11,"kind":"dup","label":2,"x":0.6461,"y":0.6288,"angle":-2.9327,"flip":true}],"wires":[{"a":[0,0],"b":[3,0]},{"a":[3,1],"b":[5,1]},{"a":[3,2],"b":[4,2]},{"a":[4,0],"b":[6,1]},{"a":[4,1],"b":[5,2]},{"a":[5,0],"b":[6,2]},{"a":[6,0],"b":[7,0]},{"a":[7,1],"b":[11,0]},{"a":[7,2],"b":[8,0]},{"a":[8,1],"b":[10,1]},{"a":[8,2],"b":[9,2]},{"a":[9,0],"b":[11,1]},{"a":[9,1],"b":[10,2]},{"a":[10,0],"b":[11,2]}],"active":[[6,7]],"rules":["dup-lam"]},{"nodes":[{"id":0,"kind":"root","label":0,"x":0.5161,"y":0.224,"angle":2.3568,"flip":false},{"id":3,"kind":"lam","label":0,"x":0.4267,"y":0.3133,"angle":-0.7848,"flip":true},{"id":4,"kind":"app","label":0,"x":0.4161,"y":0.4161,"angle":0.9361,"flip":false},{"id":5,"kind":"app","label":0,"x":0.3404,"y":0.4121,"angle":0.9235,"flip":true},{"id":8,"kind":"lam","label":0,"x":0.5813,"y":0.726,"angle":-2.4803,"flip":false},{"id":9,"kind":"app","label":0,"x":0.7039,"y":0.776,"angle":-1.4478,"flip":false},{"id":10,"kind":"app","label":0,"x":0.6868,"y":0.7006,"angle":-1.1359,"flip":true},{"id":11,"kind":"dup","label":2,"x":0.7228,"y":0.6231,"angle":-2.6249,"flip":true},{"id":12,"kind":"dup","label":1,"from":7,"x":0.5878,"y":0.5464,"angle":0.5167,"flip":true},{"id":13,"kind":"dup","label":1,"from":7,"x":0.4677,"y":0.6376,"angle":0.6613,"flip":true},{"id":14,"kind":"lam","label":0,"from":6,"x":0.4675,"y":0.4859,"angle":-2.2055,"flip":false},{"id":15,"kind":"lam","label":0,"from":6,"x":0.4389,"y":0.5424,"angle":-2.2181,"flip":false}],"wires":[{"a":[0,0],"b":[3,0]},{"a":[3,1],"b":[5,1]},{"a":[3,2],"b":[4,2]},{"a":[4,0],"b":[14,0]},{"a":[4,1],"b":[5,2]},{"a":[5,0],"b":[15,0]},{"a":[8,0],"b":[13,0]},{"a":[8,1],"b":[10,1]},{"a":[8,2],"b":[9,2]},{"a":[9,0],"b":[11,1]},{"a":[9,1],"b":[10,2]},{"a":[10,0],"b":[11,2]},{"a":[11,0],"b":[12,0]},{"a":[12,1],"b":[14,1]},{"a":[12,2],"b":[15,1]},{"a":[13,1],"b":[14,2]},{"a":[13,2],"b":[15,2]}],"active":[[4,14],[5,15],[8,13],[11,12]],"rules":["beta","beta","dup-lam","dup-dup-commute"]},{"nodes":[{"id":0,"kind":"root","label":0,"x":0.5161,"y":0.224,"angle":1.8243,"flip":false},{"id":3,"kind":"lam","label":0,"x":0.4884,"y":0.3309,"angle":-1.3173,"flip":false},{"id":9,"kind":"app","label":0,"x":0.4897,"y":0.6956,"angle":-0.9286,"flip":false},{"id":10,"kind":"app","label":0,"x":0.5086,"y":0.6073,"angle":-0.7326,"flip":true},{"id":16,"kind":"lam","label":0,"from":13,"x":0.3778,"y":0.4421,"angle":-0.7881,"flip":true},{"id":17,"kind":"lam","label":0,"from":13,"x":0.5397,"y":0.4776,"angle":0.1145,"flip":true},{"id":18,"kind":"dup","label":1,"from":8,"x":0.4365,"y":0.4928,"angle":1.0088,"flip":false},{"id":19,"kind":"dup","label":1,"from":8,"x":0.4493,"y":0.567,"angle":1.2664,"flip":false},{"id":20,"kind":"dup","label":2,"from":12,"x":0.6919,"y":0.4951,"angle":-3.0271,"flip":true},{"id":21,"kind":"dup","label":2,"from":12,"x":0.5633,"y":0.4206,"angle":-2.2665,"flip":true},{"id":22,"kind":"dup","label":1,"from":11,"x":0.585,"y":0.5682,"angle":2.213,"flip":true},{"id":23,"kind":"dup","label":1,"from":11,"x":0.6181,"y":0.5088,"angle":2.409,"flip":true}],"wires":[{"a":[0,0],"b":[3,0]},{"a":[3,1],"b":[21,0]},{"a":[3,2],"b":[16,0]},{"a":[9,0],"b":[22,0]},{"a":[9,1],"b":[10,2]},{"a":[9,2],"b":[19,0]},{"a":[10,0],"b":[23,0]},{"a":[10,1],"b":[18,0]},{"a":[16,1],"b":[18,1]},{"a":[16,2],"b":[19,1]},{"a":[17,0],"b":[20,0]},{"a":[17,1],"b":[18,2]},{"a":[17,2],"b":[19,2]},{"a":[20,1],"b":[22,1]},{"a":[20,2],"b":[23,1]},{"a":[21,1],"b":[22,2]},{"a":[21,2],"b":[23,2]}],"active":[[9,22],[10,23],[17,20]],"rules":["dup-app","dup-app","dup-lam"]},{"nodes":[{"id":0,"kind":"root","label":0,"x":0.5161,"y":0.224,"angle":1.892,"flip":false},{"id":3,"kind":"lam","label":0,"x":0.4768,"y":0.3421,"angle":-1.2496,"flip":false},{"id":16,"kind":"lam","label":0,"x":0.3677,"y":0.4125,"angle":-0.573,"flip":true},{"id":18,"kind":"dup","label":1,"x":0.4948,"y":0.4034,"angle":-0.1702,"flip":true},{"id":19,"kind":"dup","label":1,"x":0.3162,"y":0.5705,"angle":0.8899,"flip":true},{"id":21,"kind":"dup","label":2,"x":0.5628,"y":0.4701,"angle":-2.1624,"flip":true},{"id":24,"kind":"app","label":0,"from":22,"x":0.5212,"y":0.7507,"angle":-2.1034,"flip":false},{"id":25,"kind":"app","label":0,"from":22,"x":0.5526,"y":0.6312,"angle":-1.5076,"flip":false},{"id":26,"kind":"dup","label":1,"from":9,"x":0.6429,"y":0.6773,"angle":-0.6405,"flip":false},{"id":27,"kind":"dup","label":1,"from":9,"x":0.4156,"y":0.6932,"angle":-2.2517,"flip":true},{"id":28,"kind":"app","label":0,"from":23,"x":0.6825,"y":0.522,"angle":2.9321,"flip":false},{"id":29,"kind":"app","label":0,"from":23,"x":0.7001,"y":0.4502,"angle":2.9977,"flip":false},{"id":30,"kind":"dup","label":1,"from":10,"x":0.6467,"y":0.3773,"angle":2.9714,"flip":true},{"id":31,"kind":"dup","label":1,"from":10,"x":0.7568,"y":0.5924,"angle":2.501,"flip":true},{"id":32,"kind":"lam","label":0,"from":20,"x":0.4625,"y":0.6511,"angle":1.0382,"flip":true},{"id":33,"kind":"lam","label":0,"from":20,"x":0.5306,"y":0.5543,"angle":-0.2095,"flip":true},{"id":34,"kind":"dup","label":2,"from":17,"x":0.4842,"y":0.5132,"angle":-1.4746,"flip":true},{"id":35,"kind":"dup","label":2,"from":17,"x":0.4006,"y":0.6033,"angle":-2.7709,"flip":true}],"wires":[{"a":[0,0],"b":[3,0]},{"a":[3,1],"b":[21,0]},{"a":[3,2],"b":[16,0]},{"a":[16,1],"b":[18,1]},{"a":[16,2],"b":[19,1]},{"a":[18,0],"b":[30,0]},{"a":[18,2],"b":[34,0]},{"a":[19,0],"b":[27,0]},{"a":[19,2],"b":[35,0]},{"a":[21,1],"b":[25,0]},{"a":[21,2],"b":[29,0]},{"a":[24,0],"b":[32,0]},{"a":[24,1],"b":[26,1]},{"a":[24,2],"b":[27,1]},{"a":[25,1],"b":[26,2]},{"a":[25,2],"b":[27,2]},{"a":[26,0],"b":[31,0]},{"a":[28,0],"b":[33,0]},{"a":[28,1],"b":[30,1]},{"a":[28,2],"b":[31,1]},{"a":[29,1],"b":[30,2]},{"a":[29,2],"b":[31,2]},{"a":[32,1],"b":[34,1]},{"a":[32,2],"b":[35,1]},{"a":[33,1],"b":[34,2]},{"a":[33,2],"b":[35,2]}],"active":[[18,30],[19,27],[24,32],[26,31],[28,33]],"rules":["dup-dup-annihilate","dup-dup-annihilate","beta","dup-dup-annihilate","beta"]},{"nodes":[{"id":0,"kind":"root","label":0,"x":0.5161,"y":0.224,"angle":1.7213,"flip":false},{"id":3,"kind":"lam","label":0,"x":0.4987,"y":0.3387,"angle":-1.4202,"flip":false},{"id":16,"kind":"lam","label":0,"x":0.4518,"y":0.4642,"angle":-1.2132,"flip":false},{"id":21,"kind":"dup","label":2,"x":0.5576,"y":0.4713,"angle":-1.9888,"flip":true},{"id":25,"kind":"app","label":0,"x":0.5237,"y":0.62,"angle":-1.3467,"flip":false},{"id":29,"kind":"app","label":0,"x":0.6214,"y":0.5829,"angle":-2.0901,"flip":false},{"id":34,"kind":"dup","label":2,"x":0.5113,"y":0.5561,"angle":0.2388,"flip":false},{"id":35,"kind":"dup","label":2,"x":0.4081,"y":0.5895,"angle":0.258,"flip":true}],"wires":[{"a":[0,0],"b":[3,0]},{"a":[3,1],"b":[21,0]},{"a":[3,2],"b":[16,0]},{"a":[16,1],"b":[34,2]},{"a":[16,2],"b":[35,1]},{"a":[21,1],"b":[25,0]},{"a":[21,2],"b":[29,0]},{"a":[25,1],"b":[29,2]},{"a":[25,2],"b":[35,0]},{"a":[29,1],"b":[34,0]},{"a":[34,1],"b":[35,2]}],"active":[],"rules":[]}],"readback":"λf.λx.f (f (f (f x)))","counts":{"beta":5,"dup-lam":3,"dup-dup-commute":1,"dup-app":2,"dup-dup-annihilate":3},"notes":"Symmetric interaction combinators with labels (Lafont 1997 + Lamping/Asperti abstract algorithm, no oracle). lam/app are CON label 0 (ports: lam 0=principal/out,1=var,2=body; app 0=principal/func,1=arg,2=ret). dup ports 0=principal (faces the shared value),1,2=copies; labels 1 and 2 = the dup of f in each 2. One state per parallel round: 'active' = every active pair now, all rewritten in the NEXT transition, 'rules' = their rules (none at the end). New nodes carry 'from' = id of the destroyed redex node whose position they start at (commutation copies of X appear on the far side, at the partner's old position). angle = direction from node to its port-0 neighbor (y down). flip: port 1 is at angle-2pi/3 side if true, else angle+2pi/3. Positions share one global fit into [0.08,0.92]."} - bend2/docs/gen_anim.ts (18409 bytes)
#!/usr/bin/env node // The README's two page animations, media/hero.gif and media/parallel.gif. // // hero.gif is the landing page's hero: the word Bend, the purple block // blinking after it, and the one line under it. parallel.gif is the // landing page's pow2 canvas: the call splits in two, in four, ... until // one task sits on each of 64 x 64 cores; every core works its task; the // results fold back pairwise; the view zooms on the one cell that holds // the answer. // // Everything is drawn on a TRANSPARENT canvas, in the palette of the // landing page, so the tiles float on the reader's own page, light or // dark, and a reader who sees both the page and the README sees one // design. A gif has 1-bit alpha, so nothing here fades: draw or do not // draw. The hero needs an ink per theme, so it has one file per theme. // // It needs node >= 22.18, the canvas package, ffmpeg and Menlo, which // this Mac lacks: render on cluster-9d, where ~/film has all four. // // tar cf - bend2/docs/gen_anim.ts bend2/docs/gen_charts.ts \ // | ssh -J cluster cluster-9d 'cd film && tar xf -' // ssh -J cluster cluster-9d 'cd film && \ // PATH=/usr/local/node/bin:$PATH:$HOME/film node bend2/docs/gen_anim.ts' // scp -o ProxyJump=cluster 'cluster-9d:film/media/{hero,parallel}.gif' media/ import { createCanvas } from "canvas"; import { gif_write } from "./gen_charts.ts"; // Constants // ========= const MONO = "Menlo, monospace"; const PURPLE = "#8b83b5"; const BG = "#f2eee7"; const INK = "#5e5787"; const FPS = 25; // Lib // === function clamp(x: number): number { return x < 0 ? 0 : x > 1 ? 1 : x; } function ease(x: number): number { const u = clamp(x); return u * u * (3 - 2 * u); } function lerp(a: number, b: number, x: number): number { return a + (b - a) * x; } function mix(a: string, b: string, f: number): string { const pick = (h: string, i: number): number => parseInt(h.slice(1 + 2 * i, 3 + 2 * i), 16); const one = (i: number): string => String(Math.round(lerp(pick(a, i), pick(b, i), clamp(f)))); return "rgb(" + one(0) + "," + one(1) + "," + one(2) + ")"; } function gif_report(got: { out: string; frames: number; bytes: number }): void { process.stdout.write("wrote " + got.out + ": " + String(got.frames) + " frames, " + String(got.bytes) + " bytes\n"); } // Hero // ==== // The landing page's hero, as the film's title card draws it: Bend, the // purple block blinking after it, the pitch with its bold words in ink // and the rest dim, and the three claims under it. Two frames, the block // on and off, as the page blinks it every 1.1 s. One file per GitHub // theme, since a gif cannot follow the reader's: the page picks with // <picture> and prefers-color-scheme function hero(name: string, ink: string, dim: string): void { const W = 1120; const H = 250; const TITLE = 88; const PITCH: [string, boolean][] = [["a ", false], ["fast", true], [" language that ", false], ["blocks AI mistakes", true], [" via ", false], ["proof", true]]; const DOT = " \u00b7 "; const CLAIMS: [string, boolean][] = [["C", true], [" speed", false], [DOT, false], ["CUDA", true], [" parallelism", false], [DOT, false], ["Lean", true], [" proofs", false], [DOT, false], ["Python", true], [" syntax", false]]; const cv = createCanvas(W, H); const cx = cv.getContext("2d"); const font = (size: number, bold: boolean): string => (bold ? "bold " : "") + String(size) + "px " + MONO; // the run's width, then its parts, left to right from the centre function run(parts: [string, boolean][], size: number, y: number): void { let w = 0; for (const [s, bold] of parts) { cx.font = font(size, bold); w += cx.measureText(s).width; } let x = (W - w) / 2; for (const [s, bold] of parts) { cx.font = font(size, bold); cx.fillStyle = bold ? ink : dim; cx.fillText(s, x, y); x += cx.measureText(s).width; } } function draw(t: number): void { cx.clearRect(0, 0, W, H); cx.textBaseline = "alphabetic"; cx.textAlign = "left"; cx.font = font(TITLE, true); const bw = TITLE * 0.5; const tw = cx.measureText("Bend").width + TITLE * 0.11 + bw; const tx = (W - tw) / 2; const ty = 100; cx.fillStyle = ink; cx.fillText("Bend", tx, ty); if (t < 0.55) { cx.fillStyle = PURPLE; cx.fillRect(tx + tw - bw, ty - TITLE * 0.86, bw, TITLE * 0.92); } run(PITCH, TITLE * 0.36, ty + TITLE * 0.89); run(CLAIMS, TITLE * 0.264, ty + TITLE * 1.39); } gif_report(gif_write(name, cv, draw, [[0, 0.55], [0.6, 0.55]])); } // Parallel // ======== // pow2(20) splits in two, in four, ..., one task per core; each core // works its own call; the results fold back pairwise into the top-left // cell, which the view then zooms on. It is the landing page's canvas, // beat for beat, on the page's own paper and palette, so the page and // the README read as one animation. function parallel(): void { const W = 620; const N = 64; const MID = 32; const LEVELS = 12; const D0 = 0.5; const HOLD1 = 0.5; const EPRE = 0.4; const DIVE = 1.8; const EHOLD = 2.5; const BACK = 0.8; const RHOLD = 0.7; const ESTEP = 0.24; const ZMAX = 64; const ZLEN = 1.4; // what one core runs: pow2(8), call by call, the way a core runs it const STEPS = 10; const TRACE = ["pow2(8)"]; for (let d = 7; d >= 0; d--) { TRACE.push(String(256 - (1 << (d + 1)) + (1 << d)) + "+pow2(" + String(d) + ")"); } TRACE.push("256"); const TILES = ["#e4e1ec", "#d2cee1", "#bfb9d5", "#aca5c9", "#9a92be", "#8b83b5", "#6e6694"]; const SKY = TILES[0]; const split_dur = (k: number): number => 0.8 * Math.pow(0.8, k); const fold_dur = (j: number): number => 0.4 * Math.pow(0.85, j); const rung = (t: number): string => { const i = Math.min(Math.floor(t), TILES.length - 2); return mix(TILES[i], TILES[i + 1], t - i); }; const HEAT: string[] = []; for (let i = 0; i <= 16; i++) { HEAT.push(rung(2 * i / 16)); } const dims = (k: number): [number, number] => [1 << Math.ceil(k / 2), 1 << Math.floor(k / 2)]; const rnd = (i: number): number => { const s = Math.sin(i * 12.9898) * 43758.5453; return s - Math.floor(s); }; // no core starts before the camera has landed, so nothing changes // under the reader mid-dive; then they scatter by a beat const phase = (c: number, r: number): number => EPRE + DIVE + (c === MID && r === MID ? 0 : rnd(c * 7919 + r * 104729) * 0.5); let split_end = D0; for (let k = 0; k < LEVELS; k++) { split_end += split_dur(k); } const E0 = split_end + HOLD1; const R0 = E0 + EPRE + DIVE + EHOLD + BACK + RHOLD; let fold_end = R0; for (let j = 0; j < LEVELS; j++) { fold_end += fold_dur(j); } const Z0 = fold_end + 0.4; const Z1 = Z0 + ZLEN; const fold_at = (u: number): number => { let j = 0; let t = R0; while (j < LEVELS && u >= t + fold_dur(j)) { t += fold_dur(j); j++; } return j < LEVELS ? j + clamp((u - t) / fold_dur(j)) : LEVELS; }; const cv = createCanvas(W, W); const cx = cv.getContext("2d"); const gap = (s: number): number => Math.min(Math.max(s * 0.1, 1), 6); const fsz = (w: number, h: number): number => Math.min(Math.min(w, h) * 0.17, 50); function cell(x: number, y: number, w: number, h: number, fill: string): void { const g = gap(Math.min(w, h)); cx.fillStyle = fill; cx.fillRect(x + g / 2, y + g / 2, w - g, h - g); } function label(s: string, x: number, y: number, w: number, h: number, fs: number, ink: string, a: number): void { if (fs < 7 || a <= 0) { return; } cx.font = "bold " + String(fs) + "px " + MONO; if (cx.measureText(s).width > w * 0.9) { return; } cx.globalAlpha = a; cx.fillStyle = ink; cx.textAlign = "center"; cx.fillText(s, x + w / 2, y + h / 2 + fs * 0.36); cx.globalAlpha = 1; } // the k-th generation of tasks, with the seam of the cut that made it // m of the way open. No cell moves: a cut is a seam that opens down // the middle of its parent, so the picture is whole at every frame. // The label divides with the cell: at the cut, two copies of the new // call sit on the old one, and they ride apart into their own halves function slots(k: number, m: number): void { const [cols, rows] = dims(k); const w = W / cols; const h = W / rows; const [pc, pr] = k > 0 ? dims(k - 1) : [1, 1]; const pw = W / pc; const ph = W / pr; const vert = cols > pc; const g = lerp(gap(Math.min(pw, ph)), gap(Math.min(w, h)), m) / 2; cx.fillStyle = SKY; for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { const l = vert && c % 2 === 1 ? g * m : g; const q = vert && c % 2 === 0 ? g * m : g; const t = !vert && r % 2 === 1 ? g * m : g; const b = !vert && r % 2 === 0 ? g * m : g; cx.fillRect(c * w + l, r * h + t, w - l - q, h - t - b); } } // the label cannot dissolve on a gif, so the new call takes the cell // when the seam is half open, and the old one holds until then const grid = (cs: number, rs: number, name: string, a: number): void => { const gw = W / cs; const gh = W / rs; for (let r = 0; r < rs; r++) { for (let c = 0; c < cs; c++) { label(name, c * gw, r * gh, gw, gh, fsz(gw, gh), INK, a); } } }; if (k > 0 && m < 0.5) { grid(pc, pr, "pow2(" + String(21 - k) + ")", 1); } else { grid(cols, rows, "pow2(" + String(20 - k) + ")", 1); } } function draw(u: number): void { const cs = W / N; cx.clearRect(0, 0, W, W); if (u < E0) { // split let k = 0; let s = D0; while (k < LEVELS && u >= s + split_dur(k)) { s += split_dur(k); k++; } const d = split_dur(k); const cut = Math.min(0.55, d * 0.75); const p = k < LEVELS ? ease((u - (s + d - cut)) / cut) : 0; if (p > 0) { slots(k + 1, p); } else { slots(k, 1); } } else if (u < R0) { // eval const v = u - E0; const p = v < EPRE ? 0 : v < EPRE + DIVE ? ease((v - EPRE) / DIVE) : v < EPRE + DIVE + EHOLD ? 1 : 1 - ease((v - EPRE - DIVE - EHOLD) / BACK); const zs = cs * Math.exp(p * Math.log(ZMAX)); const o = W / 2 - (MID + 0.5) * zs; for (let r = 0; r < N; r++) { for (let c = 0; c < N; c++) { const x = o + c * zs; const y = o + r * zs; if (x > W || y > W || x + zs < 0 || y + zs < 0) { continue; } const j = Math.min(STEPS - 1, Math.max(0, Math.floor((v - phase(c, r)) / ESTEP))); cell(x, y, zs, zs, HEAT[Math.round(j * 16 / (STEPS - 1))]); label(TRACE[j], x, y, zs, zs, fsz(zs, zs), INK, 1); } } } else if (u < Z0) { // fold const f = fold_at(u); const j = Math.floor(f); const m = ease(f - j); const k = LEVELS - j; const [w, h] = dims(k); const vert = k % 2 === 1; const fill = rung(2 + 4 * f / LEVELS); for (let r = 0; r < h; r++) { for (let c = 0; c < w; c++) { cell((vert ? lerp(c, c / 2, m) : c) * cs, (vert ? r : lerp(r, r / 2, m)) * cs, cs, cs, fill); } } } else { // zoom const zs = cs * Math.pow(N, ease((u - Z0) / ZLEN)); cell(0, 0, zs, zs, TILES[6]); label("1048576", 0, 0, zs, zs, fsz(zs, zs), BG, u > Z1 - 0.1 ? 1 : 0); } } const shots: [number, number][] = []; const end = Z1 + 0.9; for (let i = 0; i * (1 / FPS) < end; i++) { shots.push([i / FPS, 1 / FPS]); } shots[shots.length - 1][1] = 1.8; gif_report(gif_write("parallel", cv, draw, shots)); } // Game // ==== // The landing page's three acts, one gif each. The level is a 12 x 8 map: // the flag sits in a room sealed by two walls, the player starts at // (8,5). Act one: the player walks up and bumps the room's wall, so the // law holds. Act two: the AI added the wrap feature and no law stopped // it, so the player walks off the right edge, in at the left, and takes // the flag. Act three: the law forced the AI to seal the far edge, so // the same walk stops there. const GW = 12; const GH = 8; const TILE = 64; const STEP = 0.2; const BUMP = 0.4; const BUMPS = 3; const LEAD = 0.6; const HOLD = 1.8; const PAL = { floor: ["#ebe8e2", "#e1ded7"], wall: "#8e8b87", cap: "#a8a5a1", hit: "#d9a39c", hitcap: "#e8c4bf", pole: "#87847d", cloth: "#7e9a5e", skin: "#78c0e3", eye: "#2f3b4c", win: "#f6e4e1", rim: "#dfa9a2", winink: "#c46a60" }; type Act = { name: string; far: boolean; route: [number, number][]; bump?: [number, string]; win?: boolean; pop?: string }; // the walk up the column, then along the row function up(x: number, y0: number, y1: number): [number, number][] { const p: [number, number][] = []; for (let y = y0; y >= y1; y--) { p.push([x, y]); } return p; } const ACTS: Act[] = [ { name: "game_law", far: false, route: up(8, 5, 1).concat([[7, 1], [6, 1], [5, 1], [4, 1]]), bump: [-1, "3,1"] }, { name: "game_bug", far: false, route: up(8, 5, 1).concat([[9, 1], [10, 1], [11, 1], [12, 1], [-1, 1], [0, 1], [1, 1]]), win: true, pop: "YOU WON !?" }, { name: "game_law_kept", far: true, route: up(8, 5, 1).concat([[9, 1], [10, 1]]), bump: [1, "11,1"] }, ]; function game(act: Act): void { const W = GW * TILE; const H = GH * TILE; const cv = createCanvas(W, H); const cx = cv.getContext("2d"); const near = (a: [number, number], b: [number, number]): boolean => Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) <= 1; const walk = act.route.reduce((t, c, i) => i > 0 && near(c, act.route[i - 1]) ? t + STEP : t, 0); const tail = act.bump === undefined ? 0.3 : BUMP * BUMPS; const walls = new Set<string>(); for (let y = 0; y <= 3; y++) { walls.add("3," + String(y)); } for (let x = 0; x <= 3; x++) { walls.add(String(x) + ",3"); } if (act.far) { for (let x = 0; x <= 3; x++) { walls.add(String(x) + ",7"); } for (let y = 0; y <= 3; y++) { walls.add("11," + String(y)); } } // where the player stands u seconds into the walk function at(u: number): [number, number] { let t = 0; for (let i = 0; i + 1 < act.route.length; i++) { if (!near(act.route[i], act.route[i + 1])) { continue; } if (u < t + STEP) { const f = (u - t) / STEP; return [lerp(act.route[i][0], act.route[i + 1][0], f), lerp(act.route[i][1], act.route[i + 1][1], f)]; } t += STEP; } return act.route[act.route.length - 1]; } function tile(x: number, y: number, w: number, h: number, r: nu - bend2/docs/gen_charts.ts (8582 bytes)
#!/usr/bin/env bun // The numbers the landing page and the film quote, all from the record // pins: this script measures NOTHING. Every figure comes from // bench/*/_pin_/apple_m4_max.txt, which holds only what gen_pins.ts // measured on this machine at the stamped commit. Repin first, then // quote, then draw the README's gifs (gen_gifs.ts, on a mini): // // bun bend2/docs/gen_pins.ts // bun bend2/docs/gen_charts.ts // // The site repo's front/site/index.html (beside this checkout, or at // $SITE_REPO) has chart rows that keep their ids and titles and take // their seconds from the pins; render.js's BENCH and CHECK take theirs // the same way (render the film after) and its comment names the // stamps. A checker timeout (>=300 s) is quoted as 300 and flagged // over. gen_gifs.ts imports the pin readers below: they are the one // source of every bar and figure. It also shares the GIF writer used // by gen_anim.ts and gen_gifs.ts. import * as child from "node:child_process"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; // Constants // ========= export const ROOT = path.join(import.meta.dirname, "..", ".."); export const RUNTIME_PIN = path.join(ROOT, "bench", "runtime", "_pin_", "apple_m4_max.txt"); export const CHECKER_PIN = path.join(ROOT, "bench", "checker", "_pin_", "apple_m4_max.txt"); export const CHECK_TIMEOUT = 300; function say(text: string): void { process.stdout.write(text + "\n"); } // Pins // ==== export type RunRow = { bench: string; seq: number; par: number; gpu: number; c: number; ts: number; lean: number }; export type CheckRow = { family: string; n: number; lang: string; secs: number; over: boolean }; function pin_grid(file: string, heads: string[]): [string, string[]][] { const out: [string, string[]][] = []; for (const line of fs.readFileSync(file, "utf8").split("\n")) { const row = /^\| (\S+)\s*\|(.*)\|$/.exec(line); if (row === null) { continue; } const cells = row[2].split("|").map((c) => c.trim()); if (row[1] === heads[0]) { if (cells.join(",") !== heads.slice(1).join(",")) { throw new Error(file + ": columns drifted from [" + heads.join(", ") + "] -- repin"); } continue; } out.push([row[1], cells]); } if (out.length === 0) { throw new Error(file + ": no pin rows -- repin"); } return out; } function pin_secs(cell: string): number { const got = /^(>?)([\d.]+)s/.exec(cell); if (got === null) { throw new Error("unreadable pin cell: " + cell); } return Number(got[2]); } export function pin_runtime(): RunRow[] { return pin_grid(RUNTIME_PIN, ["bench", "SEQ-CPU", "PAR-CPU", "PAR-GPU", "C", "TS", "Lean"]).map(([bench, c]) => ({ bench, seq: pin_secs(c[0]), par: pin_secs(c[1]), gpu: pin_secs(c[2]), c: pin_secs(c[3]), ts: pin_secs(c[4]), lean: pin_secs(c[5]), })); } export function pin_checker(): CheckRow[] { const langs = ["isabelle", "agda", "lean", "rocq", "bend"]; return pin_grid(CHECKER_PIN, ["bench", "Isabelle", "Agda", "Lean", "Rocq", "Bend"]).flatMap(([name, cells]) => { const cut = name.lastIndexOf("_"); const family = name.slice(0, cut); const n = Number(name.slice(cut + 1)); return langs.map((lang, i): CheckRow => ({ family, n, lang, secs: pin_secs(cells[i]), over: cells[i].startsWith(">"), })); }); } export function pin_stamp(file: string): string { const got = /^# (\d{4}-\d\d-\d\d) ([0-9a-f]+) /m .exec(fs.readFileSync(file, "utf8")); if (got === null) { throw new Error(file + ": no stamp line -- repin"); } return "(" + got[1] + ", " + got[2] + ")"; } // Front // ===== export const SITE = process.env.SITE_REPO ?? path.join(ROOT, "..", "bend-lang.com"); export const FRONT = path.join(SITE, "front", "site", "index.html"); // The landing page's chart rows: `["id", "title", secs...],`; the title // of every bench and checker family lives there, and only there. export function front_titles(): Record<string, string> { const out: Record<string, string> = {}; for (const line of fs.readFileSync(FRONT, "utf8").split("\n")) { const row = /^\s*\["([a-z0-9_-]+)", "([^"]*)",/.exec(line); if (row !== null) { out[row[1]] = row[2]; } } return out; } // Quote // ===== function quote_secs(r: { secs: number; over: boolean }): string { return r.over ? String(CHECK_TIMEOUT) : r.secs.toFixed(3); } function quote_front(runs: RunRow[], checks: CheckRow[]): void { fs.writeFileSync(FRONT, fs.readFileSync(FRONT, "utf8").split("\n") .map((line) => { const row = /^(\s*\["([a-z0-9_-]+)", "[^"]*",) [^\]]*\],$/.exec(line); if (row === null) { return line; } const run = runs.find((r) => r.bench === row[2]); const cells = run !== undefined ? [run.ts, run.lean, run.c, run.seq, run.par, run.gpu] .map((x) => x.toFixed(3)) : checks.filter((c) => c.family + "_" + String(c.n) === row[2]) .map(quote_secs); if (cells.length === 0) { throw new Error(FRONT + ": " + row[2] + " has no pin"); } return row[1] + " " + cells.join(", ") + "],"; }).join("\n")); say("wrote " + FRONT); } function quote_film(runs: RunRow[], checks: CheckRow[]): void { const file = path.join(ROOT, "bend2", "docs", "intro", "render.js"); const text = fs.readFileSync(file, "utf8"); const bench = /^const BENCH = \{\n ([a-z]+):/m.exec(text)?.[1]; const run = runs.find((r) => r.bench === bench); const family = /^\/\/ CHECK: (\S+)$/m.exec(text)?.[1]; const check = checks.filter((c) => c.family + "_" + String(c.n) === family); if (run === undefined || check.length !== 5) { throw new Error(file + ": BENCH " + String(bench) + " or CHECK " + String(family) + " has no pin"); } const names = ["Isabelle", "Agda", "Lean", "Rocq", "Bend"]; const stamps = [pin_stamp(RUNTIME_PIN), pin_stamp(CHECKER_PIN)]; fs.writeFileSync(file, text .replace(/rivals: \[[^\n]*\],/, `rivals: [["TypeScript", ${ run.ts.toFixed(3)}], ["Lean", ${run.lean.toFixed(3)}], ["C", ${ run.c.toFixed(3)}]],`) .replace(/seq: [\d.]+, par: [\d.]+, gpu: [\d.]+/, `seq: ${ run.seq.toFixed(3)}, par: ${run.par.toFixed(3)}, gpu: ${ run.gpu.toFixed(3)}`) .replace(/^const CHECK = \[[^;]*\];$/m, "const CHECK = [" + check.map( (c, i) => `["${names[i]}", ${quote_secs(c)}${c.over ? ", true" : ""}]`) .join(", ") + "];") .replace(/\(\d{4}-\d\d-\d\d, [0-9a-f]+\)/g, () => stamps.shift() ?? "")); say("wrote " + file); } // Gif // === // the frames go to ffmpeg through a concat list, which keeps every // duration, so a frame that holds is one frame with a long delay export function gif_write<T>(name: string, cv: { width: number; height: number; toBuffer: (t: "image/png") => Buffer }, draw: (t: T) => void, shots: [T, number][]): { out: string; frames: number; bytes: number } { const dir = fs.mkdtempSync(path.join(os.tmpdir(), name + "-")); const file = (i: number): string => path.join(dir, "f" + String(i).padStart(4, "0") + ".png"); let list = "ffconcat version 1.0\n"; shots.forEach(([t, d], i): void => { draw(t); fs.writeFileSync(file(i), cv.toBuffer("image/png")); list += "file '" + file(i) + "'\nduration " + String(d) + "\n"; }); list += "file '" + file(shots.length - 1) + "'\n"; fs.writeFileSync(path.join(dir, "list.txt"), list); const out = path.join(ROOT, "media", name + ".gif"); // one palette of 63 colours plus the transparent slot, no dither. // A smaller palette makes a smaller file, but it drops the green of // the speedups. A gif has 1-bit alpha: a pixel is opaque (alpha >= 128) // or clear. Because every frame keeps clear pixels, ffmpeg disposes // each one to the background, so the previous frame does not show // through const got = child.spawnSync("ffmpeg", ["-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", path.join(dir, "list.txt"), "-vf", "split[a][b];[a]palettegen=max_colors=63:reserve_transparent=1[p];" + "[b][p]paletteuse=dither=none:alpha_threshold=128", "-fps_mode", "vfr", "-loop", "0", out], { stdio: "inherit" }); if (got.status !== 0) { throw new Error("ffmpeg failed on " + name); } fs.rmSync(dir, { recursive: true }); return { out, frames: shots.length, bytes: fs.statSync(out).size }; } // Main // ==== if (import.meta.main) { const runs = pin_runtime(); const checks = pin_checker(); quote_front(runs, checks); quote_film(runs, checks); } - bend2/docs/gen_gifs.ts (8381 bytes)
#!/usr/bin/env node // The README's two charts, media/runtime.gif and media/checker.gif: the landing // page's bar chart, one bench per page, paging forever. Same look and rhythm as // the site's front/site/index.html chart(): the title above, the seconds (and // the speedup over one core) above each bar, the names below, Bend in purple, // the others in gray, a checker timeout hatched at full height with ">5 min" // above, a row of dots for the position. A page turn glides every bar to its // new height (0.6 s, ease-out) and crossfades its number; then the page holds // 2.9 s as ONE gif frame, so each bench is 3.5 s and the files stay small. // Drawn at 2x (1280 px wide) on a TRANSPARENT canvas, in colors that read on // the light and the dark GitHub, which embeds them at 640. This script measures // NOTHING: every bar is a pin read by gen_charts.ts, the titles are the site's. // // It needs node >= 22.18, the canvas package, ffmpeg and Menlo, which // this Mac lacks: render on cluster-9d, where ~/film has all four. // // bun bend2/docs/gen_pins.ts && bun bend2/docs/gen_charts.ts // tar cf - bend2/docs/gen_*.ts bench/*/_pin_/apple_m4_max.txt \ // | ssh -J cluster cluster-9d 'cd film && tar xf -' // tar cf - -C .. bend-lang.com/front/site/index.html \ // | ssh -J cluster cluster-9d 'tar xf -' # beside film: gen_charts.ts looks there // ssh -J cluster cluster-9d 'cd film && \ // PATH=/usr/local/node/bin:$PATH:$HOME/film node bend2/docs/gen_gifs.ts' // scp -o ProxyJump=cluster 'cluster-9d:film/media/*.gif' media/ import { createCanvas } from "canvas"; import * as charts from "./gen_charts.ts"; // Types // ===== type Bar = { name: string; secs: number; bend?: boolean; over?: boolean; mul?: string }; type Page = { title: string; bars: Bar[] }; // Constants // ========= // the site's chart at 16 px per em: its bars are .8 em, 10 em tall at // most, in a 35 em box, 13.5 em high here; the canvas is that, at 2x const EM = 16; const BAR_EM = 0.8 * EM; const W = 40 * EM; const H = 21 * EM; const K = 2; const BOX_BOT = 16.1 * EM; const BAR_MAX = 10 * BAR_EM; const GAP = 0.7 * EM; const NAME_H = 2.6 * BAR_EM; const FPS = 25; const GLIDE = 0.6; const HOLD = 2.9; const INK = "#87847d"; const GRAY = "#a5a29a"; const PURPLE = "#8b83b5"; const GREEN = "#7e9a5e"; const MONO = "Menlo, monospace"; const MACHINE = "Apple M4 Max · lower is better"; const cv = createCanvas(W * K, H * K); const cx = cv.getContext("2d"); cx.scale(K, K); function secs(s: number): string { return (s >= 10 ? s.toFixed(1) : s.toFixed(2)) + "s"; } function times(x: number): string { return (x >= 10 ? String(Math.round(x)) : x.toFixed(1)) + "x"; } function clamp(x: number): number { return x < 0 ? 0 : x > 1 ? 1 : x; } function ease_out(x: number): number { return 1 - Math.pow(1 - clamp(x), 3); } // Pages // ===== // every bench, best to worst by Bend's combined advantage: (one core // over the best twin) x (GPU over all cores) function pages_runtime(): Page[] { const titles = charts.front_titles(); const score = (r: charts.RunRow): number => (r.seq / Math.min(r.c, r.ts, r.lean)) * (r.gpu / r.par); return charts.pin_runtime().sort((a, b) => score(a) - score(b)) .map((r): Page => ({ title: titles[r.bench], bars: [ { name: "TypeScript", secs: r.ts }, { name: "Lean", secs: r.lean }, { name: "C", secs: r.c }, { name: "Bend\n1 core", secs: r.seq, bend: true, mul: "1x" }, { name: "Bend\n16 cores", secs: r.par, bend: true, mul: times(r.seq / r.par) }, { name: "Bend\nGPU", secs: r.gpu, bend: true, mul: times(r.seq / r.gpu) }, ] })); } // every checker family, ordered by Bend's lead over the best rival function pages_checker(): Page[] { const titles = charts.front_titles(); const names = ["Isabelle", "Agda", "Lean", "Rocq", "Bend"]; const rows = charts.pin_checker(); const pages = [...new Set(rows.map((r) => r.family))].map((family) => { const mine = rows.filter((r) => r.family === family); return { title: titles[family + "_" + String(mine[0].n)], bars: mine.map((r, i): Bar => ({ name: names[i], secs: r.secs, over: r.over, bend: r.lang === "bend" })) }; }); const lead = (p: Page): number => Math.min(...p.bars.slice(0, 4).map((b) => b.secs)) / p.bars[4].secs; return pages.sort((a, b) => lead(b) - lead(a)); } // a bar's height, as a share of the tallest: a timeout fills the chart // and halves the rest function page_heights(p: Page): number[] { const live = Math.max(...p.bars.map((b) => b.over === true ? 0 : b.secs)); const vmax = live * (p.bars.some((b) => b.over === true) ? 2 : 1); return p.bars.map((b) => b.over === true ? 1 : b.secs / vmax); } function bar_label(b: Bar): string[] { const value = b.over === true ? ">5 min" : secs(b.secs); return b.mul === undefined ? [value] : [b.mul, value]; } // Draw // ==== function text(s: string, x: number, y: number, size: number, color: string, bold = false): void { cx.font = (bold ? "bold " : "") + String(size) + "px " + MONO; cx.fillStyle = color; cx.textAlign = "center"; cx.textBaseline = "middle"; cx.fillText(s, x, y); } function hatch(x: number, y: number, w: number, h: number): void { cx.save(); cx.beginPath(); cx.rect(x, y, w, h); cx.clip(); cx.strokeStyle = GRAY; cx.lineWidth = 5.5; cx.beginPath(); for (let d = -h; d < w; d += 12.7) { cx.moveTo(x + d, y + h); cx.lineTo(x + d + h, y); } cx.stroke(); cx.restore(); } // a bar's number, and its speedup in green above it, ending 5 px over // the bar's top function label(lines: string[], alpha: number, x: number, top: number): void { cx.globalAlpha = alpha; lines.forEach((line, ln): void => { const y = top - 5 - (lines.length - ln - 0.5) * 1.25 * BAR_EM; text(line, x, y, BAR_EM, lines.length === 2 && ln === 0 ? GREEN : INK); }); cx.globalAlpha = 1; } // one frame of the turn from page a to page b, t seconds in: the bars // glide, a's numbers fade out as b's fade in, the rest is b's function frame(a: Page, b: Page, t: number, at: number, n: number): void { const ha = page_heights(a); const hb = page_heights(b); const bw = (35 * EM - (b.bars.length - 1) * GAP) / b.bars.length; const x0 = (W - 35 * EM) / 2; cx.clearRect(0, 0, W, H); text(b.title, W / 2, 1.8 * EM, EM, INK, true); b.bars.forEach((bar, i): void => { const x = x0 + i * (bw + GAP); const base = BOX_BOT - NAME_H - 6; const h = Math.max(2, BAR_MAX * (ha[i] + (hb[i] - ha[i]) * ease_out(t / GLIDE))); if (bar.over === true) { hatch(x, base - h, bw, h); } else { cx.fillStyle = bar.bend === true ? PURPLE : GRAY; cx.fillRect(x, base - h, bw, h); } const la = bar_label(a.bars[i]); const lb = bar_label(bar); if (la.join() === lb.join()) { label(lb, 1, x + bw / 2, base - h); } else { label(la, 1 - clamp(t / 0.2), x + bw / 2, base - h); label(lb, clamp((t - 0.22) / 0.4), x + bw / 2, base - h); } bar.name.split("\n").forEach((line, ln): void => { const y = BOX_BOT - NAME_H + (ln + 0.5) * 1.3 * BAR_EM; text(line, x + bw / 2, y, BAR_EM, bar.bend === true ? PURPLE : INK, bar.bend === true); }); }); for (let i = 0; i < n; i++) { const x = W / 2 + (i - (n - 1) / 2) * 1.6 * 0.87 * EM; text(i === at ? "●" : "○", x, 17.4 * EM, 0.87 * EM, i === at ? PURPLE : INK); } text(MACHINE, W / 2, 19.5 * EM, 0.87 * EM, INK); } // Gif // === // every turn is GLIDE seconds of frames at FPS; the last frame of each // turn is the page itself, and lasts HOLD seconds more function gif(name: string, pages: Page[]): void { const steps = Math.round(GLIDE * FPS); const shots: [[Page, Page, number, number], number][] = []; pages.forEach((page, at): void => { const prev = pages[(at + pages.length - 1) % pages.length]; for (let k = 1; k <= steps; k++) { shots.push([[prev, page, k / FPS, at], 1 / FPS + (k === steps ? HOLD : 0)]); } }); const got = charts.gif_write(name, cv, ([a, b, t, at]) => frame(a, b, t, at, pages.length), shots); process.stdout.write("wrote " + got.out + ": " + String(pages.length) + " pages, " + String(got.frames) + " frames, " + String(got.bytes) + " bytes\n"); } // Main // ==== gif("runtime", pages_runtime()); gif("checker", pages_checker()); - bend2/docs/gen_pins.ts (13670 bytes)
#!/usr/bin/env bun // The record pins, measured on this machine: bench/runtime/_pin_/<hw>.txt and // bench/checker/_pin_/<hw>.txt (hw from the CPU's brand string, so apple_m4_max // on the MacBook), raw seconds that gen_charts.ts draws and the landing page // and the film quote. The gate pins on the minis are gates/perf.ts --pin; this // script writes nothing it did not measure in the same run, and every Bend run // must print the output the gate pins hold. Every timed cell runs alone on a // quiet machine; only the builds run pooled, one per performance core. A // runtime row: the Bend binary built as the gate builds it (the cc lines of // gates/perf.ts) in each of its three modes, one warm run then the timed one // under /usr/bin/time -l (a fresh binary's first GPU run compiles its shader); // then the twins, warm then timed: main.c under the same cc line (an f32 sum is // not checked: -O3 fuses a*b+c), main.ts under bun and node (the faster), // main.lean under lean -c and leanc -O3. A checker row: one cold check under // Isabelle, Agda, Lean, Rocq and Bend, 300 s each, a timeout written as >300s. // Run it whole or one file at a time; --keep <lang> carries a checker column // forward from the file as it is, unmeasured (a prover this machine cannot run // today), and the stamp says so: // // bun bend2/docs/gen_pins.ts [runtime] [checker] [--keep <lang>] import * as child from "node:child_process"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import { BUILD, CC, FLAGS, MEMORY, MODES } from "../../gates/perf.ts"; // Constants // ========= const ROOT = path.join(import.meta.dirname, "..", ".."); const MAIN = path.join(ROOT, "bend2", "main.ts"); const RUNTIME = path.join(ROOT, "bench", "runtime"); const CHECKER = path.join(ROOT, "bench", "checker"); const HW = child.spawnSync("sysctl", ["-n", "machdep.cpu.brand_string"], { encoding: "utf8" }).stdout.trim().toLowerCase().replace(/\s+/g, "_"); const RUN_TIMEOUT = 600; const CHECK_TIMEOUT = 300; const LANGS = ["isabelle", "agda", "lean", "rocq", "bend"]; const POOL = ((): number => { const got = child.spawnSync("sysctl", ["-n", "hw.perflevel0.logicalcpu"], { encoding: "utf8" }); const n = Number(got.stdout.trim()); return Number.isInteger(n) && n > 0 ? n : os.cpus().length; })(); // Exec // ==== type Ran = { secs: number; out: string; over: boolean; rss: number }; function exec_run(cmd: string[], cwd: string, timeout: number, quiet = false): Promise<Ran> { return new Promise((ok, no) => { const at = performance.now(); const kid = child.spawn(cmd[0], cmd.slice(1), { cwd, detached: true, stdio: ["ignore", "pipe", "pipe"] }); let outs = ""; let errs = ""; let over = false; const timer = setTimeout(() => { over = true; try { process.kill(-(kid.pid as number), "SIGKILL"); } catch {} }, timeout * 1000); kid.stdout.on("data", (d: Buffer) => { outs += d.toString(); }); kid.stderr.on("data", (d: Buffer) => { errs += d.toString(); }); kid.on("error", (e) => { clearTimeout(timer); no(e); }); kid.on("close", (status) => { clearTimeout(timer); const secs = (performance.now() - at) / 1000; if (over) { return ok({ secs: timeout, out: "", over: true, rss: 0 }); } if (status !== 0) { if (quiet) { return ok({ secs: -1, out: "", over: false, rss: 0 }); } return no(new Error(cmd.join(" ") + " failed:\n" + outs.slice(-400) + errs.slice(-800))); } const mem = /(\d+)\s+maximum resident set size/.exec(errs); ok({ secs, out: outs.trim(), over: false, rss: mem === null ? 0 : Number(mem[1]) / (1 << 20) }); }); }); } function exec_need(bins: string[]): void { const missing = bins.filter((b) => child.spawnSync("which", [b], { encoding: "utf8" }).status !== 0); if (missing.length > 0) { throw new Error("missing toolchains: " + missing.join(", ") + " -- every pin must be measured, install them or do not repin"); } } function tmp_dir(tag: string): string { return fs.mkdtempSync(path.join(os.tmpdir(), "bend-pins-" + tag + "-")); } async function pool_run(jobs: (() => Promise<void>)[]): Promise<void> { let next = 0; await Promise.all(Array.from({ length: Math.min(POOL, jobs.length) }, async () => { while (next < jobs.length) { const job = jobs[next]; next += 1; await job(); } })); } function say(text: string): void { process.stdout.write(text + "\n"); } // Table // ===== function fmt_secs(x: number): string { return x.toFixed(3).padStart(7) + "s"; } function fmt_mem(mb: number): string { return mb < 100 ? mb.toFixed(1) + "M" : String(Math.round(mb)) + "M"; } function fmt_meas(r: Ran): string { return fmt_secs(r.secs) + " " + fmt_mem(r.rss).padStart(6); } function pin_table(heads: string[], rows: string[][]): string[] { const wide = heads.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length))); const line = (cells: string[]): string => "| " + cells.map((c, i) => c.padEnd(wide[i])).join(" | ") + " |"; return [line(heads), "|" + wide.map((w) => "-".repeat(w + 2)).join("|") + "|", ...rows.map(line)]; } function pin_write(file: string, name: string, target: string, lines: string[], kept = ""): void { const head = child.spawnSync("git", ["rev-parse", "--short", "HEAD"], { cwd: ROOT, encoding: "utf8" }).stdout.trim(); fs.writeFileSync(file, "# " + name + "\n# " + new Date().toISOString().slice(0, 10) + " " + head + " bun bend2/docs/gen_pins.ts " + target + kept + "\n\n" + lines.join("\n") + "\n"); say("wrote " + file); } // The rows of a pin file as it is, by bench, with its stamp. function pin_rows(file: string): [string, Map<string, string[]>] { const rows = new Map<string, string[]>(); let stamp = ""; for (const line of fs.readFileSync(file, "utf8").split("\n")) { const row = /^\| (\S+)\s*\|(.*)\|$/.exec(line); if (row !== null && row[1] !== "bench" && !row[2].startsWith("-")) { rows.set(row[1], row[2].split("|").map((c) => c.trim())); } else if (/^# \d{4}-/.test(line)) { stamp = /^# (\S+ \S+)/.exec(line)?.[1] ?? ""; } } return [stamp, rows]; } // Outputs // ======= // The gate pins' OUTPUT column: what every Bend run here must print. function pin_outs(): Map<string, string> { const rows = pin_rows(path.join(RUNTIME, "_pin_", "apple_m4.txt"))[1]; return new Map([...rows].map(([b, c]) => [b, c[c.length - 1]])); } // Runtime // ======= type Built = { bench: string; want: string; f32: boolean; cpu: string; gpu: string; cbin: string; lbin: string }; async function runtime_build(bench: string, want: string, dir: string): Promise<Built> { const home = path.join(RUNTIME, bench); const at = path.join(dir, bench); fs.mkdirSync(at); fs.copyFileSync(path.join(home, "main.lean"), path.join(at, "main.lean")); await exec_run([process.execPath, MAIN, path.join(home, "main.bend"), "-o", "main.c"], at, RUN_TIMEOUT); await exec_run(["sh", "-c", BUILD[0] + " -o cpu"], at, RUN_TIMEOUT); await exec_run(["sh", "-c", BUILD[2] + " -o gpu"], at, RUN_TIMEOUT); await exec_run(["sh", "-c", CC + " " + path.join(home, "main.c") + " -o twin_c"], at, RUN_TIMEOUT); await exec_run(["lean", "main.lean", "-c", "lean.c"], at, RUN_TIMEOUT); await exec_run(["leanc", "-O3", "-DNDEBUG", "lean.c", "-o", "twin_lean"], at, RUN_TIMEOUT); const f32 = fs.readFileSync(path.join(home, "main.bend"), "utf8") .includes("F32"); return { bench, want, f32, cpu: path.join(at, "cpu"), gpu: path.join(at, "gpu"), cbin: path.join(at, "twin_c"), lbin: path.join(at, "twin_lean") }; } function runtime_check(b: Built, what: string, got: Ran): Ran { if (got.out.split("\n").pop()?.trim() !== b.want) { throw new Error(b.bench + " " + what + ": output " + got.out.slice(-60) + " != the pinned " + b.want); } return got; } // A Bend binary runs in its build directory: the Metal one reads its // shader from main.c through __FILE__. async function runtime_cell(b: Built, mode: number): Promise<Ran> { const bin = mode === 2 ? b.gpu : b.cpu; const dir = path.dirname(bin); let nt = 1; while (nt * 2 <= os.cpus().length && nt < 256) { nt *= 2; } const args = FLAGS[mode].replace("$nt", String(nt)) .replace("$gm", MEMORY[b.bench] ?? "on").split(" "); await exec_run([bin, ...args], dir, RUN_TIMEOUT); return runtime_check(b, MODES[mode], await exec_run(["/usr/bin/time", "-l", bin, ...args], dir, RUN_TIMEOUT)); } async function runtime_ts(b: Built, dir: string): Promise<number> { const file = path.join(RUNTIME, b.bench, "main.ts"); await exec_run([process.execPath, file], dir, RUN_TIMEOUT); const bun = runtime_check(b, "main.ts under bun", await exec_run([process.execPath, file], dir, RUN_TIMEOUT)); await exec_run(["node", file], dir, RUN_TIMEOUT, true); const node = await exec_run(["node", file], dir, RUN_TIMEOUT, true); return node.secs >= 0 && node.out.trim().endsWith(b.want) ? Math.min(bun.secs, node.secs) : bun.secs; } async function runtime_rows(): Promise<string[][]> { exec_need(["cc", "lean", "leanc", "node"]); const outs = pin_outs(); const dir = tmp_dir("runtime"); const benches = fs.readdirSync(RUNTIME).filter((f) => !f.startsWith("_")) .sort(); const built: Built[] = []; await pool_run(benches.map((bench, i) => async () => { const want = outs.get(bench); if (want === undefined) { throw new Error(bench + ": no OUTPUT in the gate pins to check"); } built[i] = await runtime_build(bench, want, dir); })); const rows: string[][] = []; for (const b of built) { const runs = []; for (let mode = 0; mode < 3; mode += 1) { runs.push(await runtime_cell(b, mode)); } await exec_run([b.cbin], dir, RUN_TIMEOUT); const c = await exec_run([b.cbin], dir, RUN_TIMEOUT); if (!b.f32) { runtime_check(b, "main.c", c); } const ts = await runtime_ts(b, dir); await exec_run([b.lbin], dir, RUN_TIMEOUT); const lean = runtime_check(b, "main.lean", await exec_run([b.lbin], dir, RUN_TIMEOUT)); rows.push([b.bench, ...runs.map(fmt_meas), fmt_secs(c.secs), fmt_secs(ts), fmt_secs(lean.secs)]); say("runtime " + rows[rows.length - 1].join(" ")); } fs.rmSync(dir, { recursive: true, force: true }); return rows; } // Checker // ======= function checker_cell(lang: string, home: string, dir: string): Promise<Ran> { const t = CHECK_TIMEOUT; if (lang === "bend") { return exec_run([process.execPath, MAIN, path.join(home, "main.bend")], dir, t); } const ext: Record<string, string> = { lean: "lean", agda: "agda", rocq: "v", isabelle: "thy" }; fs.copyFileSync(path.join(home, "main." + ext[lang]), path.join(dir, "main." + ext[lang])); if (lang === "lean" || lang === "agda") { return exec_run([lang, "main." + ext[lang]], dir, t); } if (lang === "rocq") { return exec_run(["rocq", "compile", "main.v"], dir, t); } fs.writeFileSync(path.join(dir, "ROOT"), "session bench = HOL +\n theories\n main\n"); return exec_run(["isabelle", "build", "-c", "-D", "."], dir, t); } async function checker_rows(keep: string[]): Promise<string[][]> { exec_need(LANGS.filter((l) => l !== "bend" && !keep.includes(l))); const [, was] = pin_rows(path.join(CHECKER, "_pin_", HW + ".txt")); const rows: string[][] = []; const names = fs.readdirSync(CHECKER).filter((f) => !f.startsWith("_")) .sort().filter((n) => fs.existsSync(path.join(CHECKER, n, "main.lean"))); for (const name of names) { const row = [name]; for (const lang of LANGS) { if (keep.includes(lang)) { const cell = was.get(name)?.[LANGS.indexOf(lang)] ?? "-"; row.push(/^[\d.]+s$/.test(cell) ? fmt_secs(Number(cell.slice(0, -1))) : cell); continue; } const dir = tmp_dir(lang); const ran = await checker_cell(lang, path.join(CHECKER, name), dir) .finally(() => fs.rmSync(dir, { recursive: true, force: true })); if (lang === "bend" && !ran.out.includes("ALL PROOFS CHECK")) { throw new Error(name + ": Bend did not check: " + ran.out.slice(-200)); } row.push(ran.over ? ">" + String(CHECK_TIMEOUT) + "s" : fmt_secs(ran.secs)); say("checker " + name + " " + lang + " " + row[row.length - 1].trim()); } rows.push(row); } return rows; } // Main // ==== const args = process.argv.slice(2); const keep = args.flatMap((a, i) => args[i - 1] === "--keep" ? [a] : []); const known = ["runtime", "checker"]; if (args.some((a, i) => !known.includes(a) && a !== "--keep" && args[i - 1] !== "--keep")) { process.stderr.write("usage: bun bend2/docs/gen_pins.ts [runtime]" + " [checker] [--keep <lang>]\n"); process.exit(1); } say("pins for " + HW); const targets = known.filter((k) => args.includes(k)); for (const target of targets.length === 0 ? known : targets) { if (target === "runtime") { pin_write(path.join(RUNTIME, "_pin_", HW + ".txt"), "Runtime", target, pin_table(["bench", ...MODES, "C", "TS", "Lean"], await runtime_rows())); } else { const file = path.join(CHECKER, "_pin_", HW + ".txt"); const kept = keep.length === 0 ? "" : "; " + keep.join(", ") + " kept from " + pin_rows(file)[0] + ", not measured"; pin_write(file, "Checker", target, pin_table(["bench", "Isabelle", "Agda", "Lean", "Rocq", "Bend"], await checker_rows(keep)), kept); } } - bend2/docs/intro/index.html (2887 bytes)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Bend</title> <style> body { margin:0; background:#e9e4db; display:flex; flex-direction:column; align-items:center; font-family:Menlo,ui-monospace,monospace; color:#69665f; } canvas { margin-top:12px; border-radius:10px; box-shadow:0 2px 14px rgba(0,0,0,.12); } #bar { width:1280px; display:flex; gap:10px; align-items:center; font-size:12px; padding:8px 0; } #seek { flex:1; } #scenes { width:1280px; display:flex; gap:6px; flex-wrap:wrap; font-size:12px; } #scenes button { background:#f2eee7; color:#69665f; border:1px solid #d9d4ca; border-radius:5px; padding:4px 9px; cursor:pointer; font:inherit; } #scenes button.on { color:#8b83b5; border-color:#8b83b5; } </style> </head> <body> <canvas id="cv" width="1280" height="720"></canvas> <div id="bar"> <span id="tlab">0.0s</span> <input id="seek" type="range" min="0" max="1" step="0.02" value="0"> <span>space = play/pause · ←/→ = ±1s · click a scene to jump</span> </div> <div id="scenes"></div> <script src="render.js"></script> <script> const cv = document.getElementById("cv"); const ctx = cv.getContext("2d"); { const dpr = window.devicePixelRatio || 1; cv.width = 1280*dpr; cv.height = 720*dpr; cv.style.width = "1280px"; cv.style.height = "720px"; ctx.scale(dpr, dpr); } setCtx(ctx); let t0 = performance.now()/1000, paused = false, tPause = 0; const seek = document.getElementById("seek"), tlab = document.getElementById("tlab"); seek.max = DUR; function now() { return paused ? tPause : ((performance.now()/1000 - t0) % DUR); } function setT(t) { t = Math.max(0, Math.min(DUR - 0.01, t)); tPause = t; t0 = performance.now()/1000 - t; } const btns = SCENES.map(([name], i) => { const b = document.createElement("button"); b.textContent = i + ". " + (name.length > 17 ? name.slice(0, 17) + "\u2026" : name); b.title = T0[i].toFixed(1) + "s"; b.onclick = () => setT(T0[i] + 0.01); document.getElementById("scenes").appendChild(b); return b; }); function frame() { const t = now(); draw(t); seek.value = t; tlab.textContent = t.toFixed(1) + "s / " + DUR + "s"; let cur = 0; while (cur < T0.length - 1 && t >= T0[cur + 1]) cur++; btns.forEach((b, i) => b.className = i === cur ? "on" : ""); requestAnimationFrame(frame); } seek.addEventListener("input", () => setT(parseFloat(seek.value))); cv.addEventListener("click", () => { paused ? setT(tPause) : (tPause = now()); paused = !paused; }); window.addEventListener("keydown", e => { if (e.code === "Space") { e.preventDefault(); cv.click(); } if (e.code === "ArrowRight") { e.preventDefault(); setT(now() + 1); } if (e.code === "ArrowLeft") { e.preventDefault(); setT(now() - 1); } }); const hash = location.hash.match(/t=([\d.]+)/); if (hash) { paused = true; tPause = parseFloat(hash[1]); } frame(); </script> </body> </html> - bend2/docs/intro/package.json (278 bytes)
{ "name": "bend-intro", "private": true, "description": "The Bend intro film: render.js is the film, index.html plays it, video.js writes media/intro.mp4 and media/intro.gif, shots.js prints stills.", "type": "commonjs", "dependencies": { "canvas": "^3.2.3" } } - bend2/docs/intro/render.js (39645 bytes)
"use strict"; // Bend explainer. // Rules: a screen is EITHER one sentence OR one picture, never both. // One new thing per beat, held long enough to read it out loud twice. // In a sentence, *stars* mark the words that carry the idea, +plus+ is // green, /slash/ leans, a line that starts with ~ is a dim // aside, a line that starts with # is a title, and an empty line is a // breath of space. // Twin lines are written to the same length, so a slide reads as one block. // // PACING BASELINE, measured on a real reader: a new word costs 0.32s to read; // a number costs double, because it is read digit by digit. A sentence beat // computes its own length AND when each of its lines appears -- a line lands // only once the line above it has been read -- then holds one breath plus // 25% of the whole reading time, the look-back over the finished slide. A // picture beat is given the seconds its motion needs plus a HOLD of >= 2.5s. // A slide marked "punch" is a punchline: it holds 30% longer. A slide marked // "quick" is a section title: it holds one breath and no look-back. A slide // marked "red" or "green" is written in that ink. const READ = 0.32; const cost = s => (s = s.replace(/[*+~#%/]/g, "").trim()) ? s.split(/\s+/) .reduce((n, w) => n + (/\d/.test(w) ? 2 : 1), 0) : 0; const co = "co", punch = "punch", quick = "quick", left = "left", red = "red", green = "green"; const TAG = new Set([co, punch, quick, left, red, green]); const BEATS = [ ["say", "Imagine a programming language", "where AIs couldn't write bugs?"], ["say", "#Introducing...", quick], ["title"], ["say", "First, let's talk about *speed*."], ["check"], ["bench", "gameoflife"], ["par", "gameoflife", co], ["say", "#Bend runs on GPUs."], ["dist"], ["eval", co], ["reduce", co], ["say", "Objects, arrays, allocator, collector,", "pattern-matching, closures, recursion.", "", "*The whole language* compiles to *kernels*!"], ["say", "Bend is fast on a single CPU core.", "And scales to massive GPU clusters."], ["say", "How about *vibe-coding*?"], ["say", "In Bend,", "you can *stop models*", "from *making mistakes*", "by demanding *proofs*."], ["say", "#How?"], ["reveal", "LAWS|.|bend", 64], ["say", "A new file that lists *invariants*", "that models are *forced* to follow."], ["say", "For example, consider a game with one law:", "%\"the player can't win\""], ["laws"], ["say", "Let's see it in action!"], ["intro"], ["say", "So far, it works as intended!"], ["say", "Now, let's *prompt* a new feature:", "%\"please, make the board wrap around\""], ["say", "Without *LAWS.bend*:"], ["walk"], ["say", "Oops! The new feature *introduced a bug*.", "Nothing stopped the AI from *breaking the laws*.", red], ["say", "With *LAWS.bend*:"], ["block"], ["say", "The AI placed a wall!", "The new feature landed with *no bugs*.", green], ["say", "But *why*?"], ["say", "Because the rules in *LAWS.bend* are enforced", "by a *proof checking* algorithm - as in Lean!", "", "If the AI makes any *mistake*,", "Bend forces it to *try again*.", "", "It is *mathematically impossible* to merge a bug!"], ["say", "*LAWS.bend* == *AGENTS.md*", "except backed by *proof*"], ["say", "With *LAWS.bend*,", "%\"make no mistakes\"", "becomes +enforceable+.", punch], ["say", "And that's Bend:", "a language *fast* like C", "that *scales* like CUDA", "that *proves* like Lean", "where vibe-coding *works*."], ["end"], ]; const W = 1280, H = 720; // the landing page's palette: its page, its inks, its code panel, and // purple for Bend, green for gains and good news, red for bad news const BG = "#f2eee7", INK = "#4d4a44", TEXT = "#69665f", DIM = "#87847d", FAINT = "#a9a59d"; const CARD = "#e9e4db", GREEN = "#7e9a5e", RED = "#c46a60", PURPLE = "#8b83b5", ORANGE = "#c4845c"; const AMBER = "#b7924b", GRAY = "#cdc7bc", SKY = "#e4e1ec", MIST = "#e6e1d8"; const MONO = "Menlo,ui-monospace,monospace"; let cx = null; function setCtx(c) { cx = c; } // ------------------------------------------------------------------ helpers const clamp = (x, a, b) => x < a ? a : x > b ? b : x; const ease = x => { x = clamp(x, 0, 1); return x*x*(3 - 2*x); }; const lerp = (a, b, x) => a + (b - a)*x; const num = x => Math.round(x).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); const rnd = i => { const s = Math.sin(i*12.9898)*43758.5453; return s - Math.floor(s); }; function font(size, bold) { cx.font = (bold ? "bold " : "") + size + "px " + MONO; } function T(s, x, y, size, color, align, bold) { font(size, bold); cx.fillStyle = color; cx.textAlign = align || "left"; cx.fillText(s, x, y); cx.textAlign = "left"; } // centred sentence with emphasis: *bold* +green+ /oblique/ // (Menlo has no italic, so an oblique run is the text leaned by a skew) function richToks(s) { const toks = []; for (let i = 0; i < s.length; ) { const c = s[i], j = "*+/".includes(c) ? s.indexOf(c, i + 1) : -1; if (j > i) { toks.push([s.slice(i + 1, j), c]); i = j + 1; continue; } let e = i + 1; while (e < s.length && !"*+/".includes(s[e])) e++; toks.push([s.slice(i, e), ""]); i = e; } return toks; } const bold = m => !!m && m !== "/"; function richW(s, size) { return richToks(s).reduce((t, [p, m]) => { font(size, bold(m)); return t + cx.measureText(p).width; }, 0); } function rich(s, x, y, size, color, plain) { let px = x - richW(s, size)/2; richToks(s).forEach(([p, m]) => { font(size, bold(m)); cx.fillStyle = m === "+" ? GREEN : m || !plain ? (color || INK) : plain; if (m === "/") { cx.save(); cx.transform(1, 0, -0.2, 1, 0.2*y, 0); } cx.fillText(p, px, y); px += cx.measureText(p).width; if (m === "/") cx.restore(); }); } function box(x, y, w, h, r, fill, stroke, lw) { cx.beginPath(); cx.roundRect(x, y, Math.max(w, 0.5), Math.max(h, 0.5), r); if (fill) { cx.fillStyle = fill; cx.fill(); } if (stroke) { cx.strokeStyle = stroke; cx.lineWidth = lw || 1; cx.stroke(); cx.lineWidth = 1; } } // a bowed arrow: a curve from (x0,y0) to (x1,y1) that bulges k of its // length to the side (k < 0: the other side), drawn up to fraction a of it. // With via, the curve bends through that control point instead, so the // head points the way via -> tip runs. function bow(x0, y0, x1, y1, k, color, a, via) { const A = a === undefined ? 1 : clamp(a, 0, 1); if (A <= 0) return; const dx = x1 - x0, dy = y1 - y0; const [mx, my] = via || [(x0 + x1)/2 - k*dy, (y0 + y1)/2 + k*dx]; const n = 24, P = []; for (let i = 0; i <= n; i++) { const t = A*i/n, s = 1 - t; P.push([s*s*x0 + 2*s*t*mx + t*t*x1, s*s*y0 + 2*s*t*my + t*t*y1]); } cx.strokeStyle = color; cx.lineWidth = 2.5; cx.lineCap = "round"; cx.lineJoin = "round"; cx.beginPath(); P.forEach(([x, y], i) => i ? cx.lineTo(x, y) : cx.moveTo(x, y)); cx.stroke(); const [ex, ey] = P[n], [px, py] = P[n - 1], l = Math.hypot(ex - px, ey - py) || 1; const ux = (ex - px)/l, uy = (ey - py)/l; cx.beginPath(); cx.moveTo(ex - 13*ux + 7*uy, ey - 13*uy - 7*ux); cx.lineTo(ex, ey); cx.lineTo(ex - 13*ux - 7*uy, ey - 13*uy + 7*ux); cx.stroke(); cx.lineWidth = 1; } // ------------------------------------------------------------------ code const KW = new Set(["def", "type", "is", "Data", "match", "case", "import", "as", "law", "do", "return"]); const QUANT = new Set(["for", "exs"]), CTR = new Set(["True", "False"]); function codeLine(s, x, y, size) { font(size); const re = /("[^"]*"|#.*$|[A-Za-z_][A-Za-z0-9_.]*|\d+n?|\s+|.)/g; let m, px = x, prev = ""; while ((m = re.exec(s)) !== null) { const t = m[0], kw = KW.has(t) || QUANT.has(t), name = prev === "def" || prev === "law"; font(size, kw); cx.fillStyle = t[0] === "#" ? FAINT : t[0] === "\"" || CTR.has(t) ? ORANGE : kw ? GREEN : name ? PURPLE : TEXT; cx.fillText(t, px, y); px += cx.measureText(t).width; if (t.trim()) prev = t; } font(size); } // a file card: a gray page with the lines, the same margin above the // first line's caps as below the last line's descenders const cardH = (n, pitch) => n*pitch + 30; function codeCard(lines, x, y, w, size, pitch) { box(x, y, w, cardH(lines.length, pitch), 10, CARD); lines.forEach((l, i) => codeLine(l, x + 28, y + 36 + i*pitch, size)); } // LAWS.bend, for the reader, as the landing page shows it: the namespaces // and the equality's braces are left out (that sugar comes later); each // line of the law gets a gloss const LAWS_SRC = `# LAW: no move sequence leads to victory. law you_cant_win: for moves: List<Move> board = replay(start(), moves) is_won(board) == False`.split("\n"); const LAWS_GLOSS = ["LAW: You Can't Win", "\"for any sequence of moves\"", "\"replaying it from the start\"", "\"can never lead to victory\""]; // ------------------------------------------------------------------ benches // Every number is a pin from bench/runtime/_pin_/apple_m4_max.txt // (2026-09-17, d0db7b3e) and bench/checker/_pin_/apple_m4_max.txt // (2026-09-09, f655a39d), the landing page's numbers: the same Bend binary // on one core, on all 16 cores, and on the GPU, against its native twins // in C, TypeScript and Lean. const BENCH = { gameoflife: { title: "game of life", rivals: [["TypeScript", 18.754], ["Lean", 13.849], ["C", 6.776]], seq: 7.803, par: 0.647, gpu: 0.063 }, }; // CHECK: generics_3200 const CHECK = [["Isabelle", 300, true], ["Agda", 300, true], ["Lean", 19.214], ["Rocq", 6.038], ["Bend", 0.384]]; const secs = s => (s >= 10 ? s.toFixed(1) : s.toFixed(2)) + "s"; const times = x => (x >= 10 ? Math.round(x) : x.toFixed(1)) + "x"; const BASE = 545, BARH = 330, BW = 110; const slotX = (i, n, gap) => W/2 - (n*BW + (n - 1)*gap)/2 + i*(BW + gap); const barTop = (v, vmax) => BASE - BARH*v/vmax; // one bar: rises from the baseline, its value above, its name below function bar(x, v, vmax, name, color, a, over, mul) { const m = mul === undefined ? 1 : mul; if (a <= 0 || m <= 0) return; const h = BARH*v/vmax*ease(a); cx.globalAlpha = m; if (over) { box(x, BASE - h, BW, h, 4, "#efebe4"); cx.save(); cx.beginPath(); cx.rect(x, BASE - h, BW, h); cx.clip(); cx.strokeStyle = GRAY; cx.lineWidth = 2; cx.beginPath(); for (let d = -h; d < BW; d += 12) { cx.moveTo(x + d, BASE); cx.lineTo(x + d + h, BASE - h); } cx.stroke(); cx.restore(); cx.lineWidth = 1; } else box(x, BASE - h, BW, h, 4, color); cx.globalAlpha = m*ease((a - 0.5)/0.5); T(over ? ">5 min" : secs(v), x + BW/2, BASE - h - 14, 22, INK, "center", true); T(name, x + BW/2, BASE + 32, 20, color === PURPLE ? PURPLE : DIM, "center", color === PURPLE); cx.globalAlpha = 1; } // one readout straight above a parallel bar: the speedup, the cores it // took, and an arrow down to the bar const G3 = 150, SPY = 280; // the readout lands in steps: "11x faster"; then "on"; then a count that // runs from 1 up to the core count (the GPU's pauses at 16, then runs on // to 16384); then the chip, then "cores". The line is laid out for the // final count, so nothing shifts as it runs function speedup(B, v, i, counts, chip, u, t0) { const a = ease((u - t0)/0.6); if (a <= 0) return; const x = slotX(i, 3, G3) + BW/2, T1 = t0 + 0.5, T2 = T1 + 0.4, RUN = 0.8, PAUSE = 0.4, RUN2 = 1.6; cx.globalAlpha = a; T(times(B.seq/v) + " faster", x, SPY + 6*(1 - a), 26, GREEN, "center", true); let n = Math.round(lerp(1, counts[0], clamp((u - T2)/RUN, 0, 1))), tEnd = T2 + RUN; if (counts[1]) { if (u > tEnd + PAUSE) n = Math.round(lerp(counts[0], counts[1], clamp((u - tEnd - PAUSE)/RUN2, 0, 1))); tEnd += PAUSE + RUN2; } font(20); const onW = cx.measureText("on ").width; font(20, true); const numW = cx.measureText(String(counts[counts.length - 1])).width, chipW = cx.measureText(" " + chip).width, coresW = cx.measureText(" cores").width; const oa = ease((u - T1)/0.4), na = ease((u - T2)/0.3), ca = ease((u - tEnd - 0.4)/0.4), ka = ease((u - tEnd - 0.8)/0.4), y = SPY + 30; let px = x - (onW + numW + chipW + coresW)/2; cx.globalAlpha = oa; T("on ", px, y + 6*(1 - oa), 20, GREEN, "left"); px += onW; cx.globalAlpha = na; T(String(n), px, y + 6*(1 - na), 20, GREEN, "left", true); px += numW; cx.globalAlpha = ca; T(" " + chip, px, y + 6*(1 - ca), 20, GREEN, "left", true); px += chipW; cx.globalAlpha = ka; T(" cores", px, y + 6*(1 - ka), 20, GREEN, "left", true); cx.globalAlpha = a; bow(x, SPY + 48, x, barTop(v, B.seq) - 44, -0.2, GREEN, a); cx.globalAlpha = 1; } const S = {}; // the chart: the three rivals and Bend, rising one at a time if rise; as // go climbs the rivals fade, Bend slides to the left slot and the axis // zooms onto it. Returns the axis. function chart(B, u, go, rise) { const all = B.rivals.concat([["Bend", B.seq]]); const vmax = Math.max(...all.map(r => r[1])), vz = lerp(vmax, B.seq, go); rich("Bend runs *FAST*", W/2, 96, 30); all.forEach(([name, v], i) => { const a = rise ? ease((u - 1.0 - i*1.0)/0.5) : 1; if (i < 3) bar(slotX(i, 4, 70), v, vmax, name, GRAY, a, false, 1 - go); else bar(lerp(slotX(3, 4, 70), slotX(0, 3, G3), go), v, vz, "Bend", PURPLE, a); }); cx.globalAlpha = rise ? ease((u - 5.2)/0.5) : 1; T(B.title + " · Apple M4 Max", W/2, 640, 20, DIM, "center"); cx.globalAlpha = 1; return vz; } // four bars, one at a time, then the machine, then Bend's bar pointed out S.bench = (u, dur, b) => { const B = BENCH[b[2]], vmax = Math.max(...B.rivals.map(r => r[1]), B.seq); chart(B, u, 0, true); const pa = ease((u - 6.2)/0.5)*(1 - ease((u - dur + 0.6)/0.4)); cx.globalAlpha = pa; T("Competes with C", 930, 250, 26, GREEN, "center", true); T("on a single core", 930, 282, 26, GREEN, "center", true); bow(940, 305, slotX(3, 4, 70) + BW/2, barTop(B.seq, vmax) - 42, -0.2, GREEN, pa); cx.globalAlpha = 1; }; // the same chart: the rivals leave, then the 16-core bar rises and its // readout lands, then the GPU's bar and readout; both readouts stay S.par = (u, dur, b) => { const B = BENCH[b[2]], vz = chart(B, u, ease((u - 0.6)/0.9), false); bar(slotX(1, 3, G3), B.par, vz, "Bend", PURPLE, ease((u - 2.0)/0.5)); speedup(B, B.par, 1, [16], "CPU", u, 2.8); bar(slotX(2, 3, G3), B.gpu, vz, "Bend", PURPLE, ease((u - 5.6)/0.5)); speedup(B, B.gpu, 2, [16, 16384], "GPU", u, 6.4); }; // five bars, then the gap between Bend and the field, pointed out S.check = (u, dur) => { const vmax = 2*19.557; rich("Bend compiles *FAST*", W/2, 96, 30); CHECK.forEach(([name, v, over], i) => bar(slotX(i, 5, 70), over ? vmax : v, vmax, name, name === "Bend" ? PURPLE : GRAY, ease((u - 1.0 - i*1.0)/0.5), over)); cx.globalAlpha = ease((u - 6.2)/0.5); T("3,200 generic instantiations · Apple M4 Max", W/2, 640, 20, DIM, "center"); const pa = ease((u - 7.4)/0.5); cx.globalAlpha = pa; T("Up to 100x faster", 930, 330, 26, GREEN, "center", true); T("than other provers", 930, 362, 26, GREEN, "center", true); bow(950, - bend2/docs/intro/shots.js (750 bytes)
// stills: node shots.js 6:3.5 7:10 -> shots/b06_3.5.png (beat 6 at 3.5s) const { createCanvas } = require("canvas"); const fs = require("fs"); const { draw, setCtx, DUR, SCENES, T0 } = require("./render.js"); const cv = createCanvas(1280, 720); setCtx(cv.getContext("2d")); fs.mkdirSync("shots", { recursive: true }); if (process.argv.length < 3) { SCENES.forEach(([n, d], i) => console.log(String(i).padStart(2), T0[i].toFixed(1).padStart(6), d.toFixed(1).padStart(5), n)); console.log("DUR", DUR.toFixed(1)); } for (const a of process.argv.slice(2)) { const [b, o] = a.split(":").map(Number); draw(T0[b] + o); const f = `shots/b${String(b).padStart(2, "0")}_${o}.png`; fs.writeFileSync(f, cv.toBuffer("image/png")); console.log(f); } - bend2/docs/intro/video.js (2321 bytes)
// Renders the film. Usage: // node video.js media/intro.mp4 (1920x1080, 60fps) and media/intro.gif (640px wide, 20fps) // node video.js 3 9 26 stills at those seconds into shots/ // Frames stream straight into ffmpeg; nothing lands on disk but the outputs. const { createCanvas } = require("canvas"); const fs = require("fs"), path = require("path"), { spawn, spawnSync } = require("child_process"); const { draw, setCtx, DUR } = require("./render.js"); // the film is drawn in 1280x720 units; the canvas is that, scaled to 1080p const K = 1.5, W = 1280*K, H = 720*K, FPS = 60, OUT = path.join(__dirname, "..", "..", "..", "media"); const cv = createCanvas(W, H), ctx = cv.getContext("2d"); ctx.scale(K, K); setCtx(ctx); const args = process.argv.slice(2); if (args.length) { fs.mkdirSync("shots", { recursive: true }); for (const a of args) { draw(parseFloat(a)); fs.writeFileSync(`shots/t${a}.png`, cv.toBuffer("image/png")); console.log(`shots/t${a}.png`); } } else (async () => { const mp4 = path.join(OUT, "intro.mp4"), gif = path.join(OUT, "intro.gif"), N = Math.round(DUR*FPS); const ff = spawn("ffmpeg", ["-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "bgra", "-s", `${W}x${H}`, "-r", String(FPS), "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-movflags", "+faststart", mp4], { stdio: ["pipe", "ignore", "inherit"] }); for (let f = 0; f < N; f++) { draw(f/FPS); if (!ff.stdin.write(cv.toBuffer("raw"))) await new Promise(r => ff.stdin.once("drain", r)); if (f % 1800 === 0) console.log(`${f}/${N}`); } ff.stdin.end(); await new Promise(r => ff.on("close", r)); // the gif: one 48-colour palette for the whole film, ordered dither, frames // diffed by ffmpeg, 640px (the README column) at 20fps (one frame in // three) throughout. The cube's camera moves change every pixel every // frame; this is what keeps the whole under GitHub's 10 MB (30fps would // be 16 MB, 64 colours 11 MB) spawnSync("ffmpeg", ["-y", "-loglevel", "error", "-i", mp4, "-vf", "select='not(mod(n,3))',scale=640:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=48[p];[b][p]paletteuse=dither=bayer:bayer_scale=5", "-fps_mode", "vfr", gif], { stdio: "inherit" }); console.log("done: " + mp4 + " " + gif); })(); - bend2/effs/args.js (630 bytes)
// IO // == function io_args() { let xs = { $: CID(Nil) }; for (let i = cli_args.length; i > 0; i -= 1) { xs = { $: CID(Con), head: cli_args[i - 1], tail: xs }; } return xs; } // Node and Bun decode the arguments before a program sees them, so here a // byte that isn't UTF-8 arrives as U+FFFD's UTF-8, EF BF BD. function io_args_bytes() { let xs = { $: CID(Nil) }; for (let i = cli_args.length; i > 0; i -= 1) { const b = io_bytes(cli_args[i - 1]); xs = { $: CID(Con), head: io_list(b, b.length), tail: xs }; } return xs; } io_eff(CID(IO.args), io_args); io_eff(CID(IO.args_bytes), io_args_bytes); - bend2/effs/audio_close.js (118 bytes)
// Audio // ===== function audio_close(audio) { return { $: CID(Unit) }; } io_eff(CID(Audio.close), audio_close); - bend2/effs/audio_open.js (351 bytes)
// Audio // ===== // A silent device: the ring's queue drains by the clock. function audio_open(rate) { if (rate < 8000 || rate > 192000) { return io_fail(22); } // tests/io/audio_whole_frames.js pauses its device through the rate field. return io_done({ rate, queued: 0, at: performance.now() }); } io_eff(CID(Audio.open), audio_open); - bend2/effs/audio_write.js (835 bytes)
// Audio // ===== const AUDIO_RING = 4096; // Frames; matches IO_RING in audio.c. function audio_write(audio, samples) { let n = 0; for (let xs = samples; xs.$ === CID(Con); xs = xs.tail) { n += 1; } const frames = Math.floor(n / 2); const now = performance.now(); const drained = Math.floor((now - audio.at) * audio.rate / 1000); audio.queued = Math.max(0, audio.queued - drained); // Carry subframe time while playing; idle time cannot drain future writes. audio.at = audio.queued === 0 || audio.rate === 0 ? now : audio.at + drained * 1000 / audio.rate; // Complete stereo frames only; oversized writes are dropped whole. if (n <= AUDIO_RING * 2 && audio.queued + frames <= AUDIO_RING) { audio.queued += frames; } return io_tup(audio, audio.queued); } io_eff(CID(Audio.write), audio_write); - bend2/effs/chan.js (6970 bytes)
// Chan // ==== // Chan.new, send, recv, close and the try_ twins share this file. // A parked receiver holds CHAN_RECV: the C lane parks TERM_HOLE, and a // program can make neither. A sent value may be null (an erased proof). const CHAN_RECV = Symbol(); function chan_done() { return { $: CID(Done), value: { $: CID(Unit) } }; } function chan_wait(item) { return { $: CID(Wait), rest: item === CHAN_RECV ? { $: CID(Unit) } : item }; } // The buffer and the waiters are queues, xs[head..]: Array.shift drains n in // n^2 on V8, so a pull moves head, and compacts once head passes the live // ones + 64, so a pull moves O(1) of them. function q_new() { return { xs: [], head: 0 }; } function q_size(q) { return q.xs.length - q.head; } function q_push(q, x) { q.xs.push(x); } function q_pull(q) { const x = q.xs[q.head]; q.xs[q.head] = undefined; q.head += 1; const live = q_size(q); if (live === 0 || q.head > live + 64) { q.xs.copyWithin(0, q.head); q.xs.length = live; q.head = 0; } return x; } // A waiter that will never wake: gone, or its IO has returned. function chan_dead(w) { return w.gone || w.io.done; } // The first waiter, past those whose IO has returned (a nested io_run): their // computations are gone with it, so the row drops them and their items; and // past those whose try_ timer came first, which left without a wake. function chan_head(row) { let w = row.wait.xs[row.wait.head]; while (w !== undefined && chan_dead(w)) { row.dead -= w.gone ? 1 : 0; q_pull(row.wait); w = row.wait.xs[row.wait.head]; } return w; } // Where timer t is in ws, which io_park_on keeps sorted by at: a binary search // to the first timer due at t.at, then past others due at the same time. -1 if // the poller has taken it. function chan_timer(ws, t) { let i = 0; for (let hi = ws.length; i < hi;) { const mid = (i + hi) >> 1; if (ws[mid].at < t.at) i = mid + 1; else hi = mid; } while (i < ws.length && ws[i] !== t && ws[i].at === t.at) i += 1; return ws[i] === t ? i : -1; } // Wakes the first live waiter with x, as Ready{x} if try_ (cutting its timer, // if the poller has not taken it yet), on the IO that parked it: a nested // io_run may wake an outer one. function chan_wake(row, x) { const w = chan_head(row); q_pull(row.wait); w.gone = true; row.keep -= row.keep > 0 ? 1 : 0; if (w.late !== undefined) { const ws = w.io.waits; const i = chan_timer(ws, w.timer); if (i >= 0) ws.splice(i, 1); x = { $: CID(Ready), value: x }; } io_push(w.cont, x, false, w.io); return w.item; } function chan_take(row) { const v = q_pull(row.ring); if (chan_head(row) !== undefined) { q_push(row.ring, chan_wake(row, chan_done())); } return v; } // A handle is the row (a stale copy keeps it, shut). function chan_shut(row) { row.shut = true; for (let w; (w = chan_head(row)) !== undefined;) { chan_wake(row, w.item === CHAN_RECV ? { $: CID(None) } : { $: CID(Fail), error: w.item }); } } // Drops the waiters that will never wake, with their items, in one pass. // keep is how many were left; each wake lowers it, so it may fall under the // live ones, but never rises until the next shed. function chan_shed(row) { const q = row.wait; let n = 0; for (let i = q.head; i < q.xs.length; i += 1) { if (!chan_dead(q.xs[i])) q.xs[n++] = q.xs[i]; } q.xs.length = n; q.head = 0; row.dead = 0; row.keep = n; } // A late w stays in the queue, gone and holding nothing, for chan_head to // drop when it comes first. Once the gone outnumber the rest by 64, the // queue sheds them all, so a timeout costs O(1) and the gone stay under // the rest+64, even behind a waiter that is never woken. The rest counts // waiters whose IO returned, which chan_park bounds. function chan_late(row, w) { w.gone = true; w.io = w.cont = w.item = w.late = w.timer = undefined; row.dead += 1; if (row.dead > q_size(row.wait) - row.dead + 64) chan_shed(row); } // Parks k on row with item; with ms, a timer too, whose late answers Wait: // the first of the two to come cuts the other. A waiter whose IO returns is // not counted dead, so a park sheds once the queue passes twice keep + 64, // at O(1) a park. Behind a live waiter, those stay under twice the waiters // live at the last shed + 64 (not the live now: a waiter kept there may have // lost its IO since), and go only at a later park on row. function chan_park(row, k, item, ms) { if (q_size(row.wait) > row.keep * 2 + 64) chan_shed(row); const w = { io: io_active, cont: k, item: item, gone: false }; if (ms !== undefined) { w.late = () => { // An earlier callback of the same ready batch may have woken w. if (w.gone) return undefined; chan_late(row, w); return chan_wait(item); }; w.timer = io_park_on(undefined, false, k, w.late, io_until(ms)); } q_push(row.wait, w); return undefined; } // Sends without waiting: Done{}, Fail{v} if closed, undefined if it would. function chan_put(row, value) { if (row.shut) { return { $: CID(Fail), error: value }; } if (chan_head(row)?.item === CHAN_RECV) { chan_wake(row, { $: CID(Some), value: value }); return chan_done(); } if (q_size(row.ring) < row.room) { q_push(row.ring, value); return chan_done(); } return undefined; } // Receives without waiting: Some{v}, None{} at the end, undefined if not. function chan_get(row) { if (q_size(row.ring) > 0) { return { $: CID(Some), value: chan_take(row) }; } const w = chan_head(row); if (w !== undefined && w.item !== CHAN_RECV) { return { $: CID(Some), value: chan_wake(row, chan_done()) }; } if (row.shut) { return { $: CID(None) }; } return undefined; } // Ready{x} now, Wait{rest} now if ms is 0, else parks until a wake or ms. function chan_try(row, x, item, ms, k) { if (x !== undefined) { return { $: CID(Ready), value: x }; } if (Number(ms) === 0) { return chan_wait(item); } return chan_park(row, k, item, Number(ms)); } function chan_new(room) { return { room: Number(room), ring: q_new(), wait: q_new(), dead: 0, keep: 0, shut: false }; } function chan_send(row, value, k) { const x = chan_put(row, value); return x !== undefined ? x : chan_park(row, k, value); } function chan_recv(row, k) { const x = chan_get(row); return x !== undefined ? x : chan_park(row, k, CHAN_RECV); } function chan_try_send(row, value, ms, k) { return chan_try(row, chan_put(row, value), value, ms, k); } function chan_try_recv(row, ms, k) { return chan_try(row, chan_get(row), CHAN_RECV, ms, k); } function chan_close(row) { if (!row.shut) { chan_shut(row); } return { $: CID(Unit) }; } io_eff(CID(Chan.new), chan_new); io_eff(CID(Chan.send), chan_send); io_eff(CID(Chan.recv), chan_recv); io_eff(CID(Chan.try_send), chan_try_send); io_eff(CID(Chan.try_recv), chan_try_recv); io_eff(CID(Chan.close), chan_close); - bend2/effs/file_close.js (223 bytes)
// File // ==== function file_close(file) { const fs = require("fs"); try { fs.closeSync(file); } catch (e) { } io_file_append.delete(file); return { $: CID(Unit) }; } io_eff(CID(File.close), file_close); - bend2/effs/file_open.js (960 bytes)
// File // ==== // name is the path's bytes, or null if a value is past 255. function file_open_with(name, mode) { if (name === null) { return io_fail(22); } if (name.includes(0)) { return io_fail(process.platform === "darwin" ? 92 : 84); } if (!["r", "r+", "w", "a", "x"].includes(mode)) { return io_fail(22); } try { // Node spells "x" as "wx". const fd = require("fs").openSync(name.length > 0 ? Buffer.from(name) : "", mode === "x" ? "wx" : mode, 0o644); if (mode === "a") { io_file_append.add(fd); } return io_done(fd); } catch (e) { return io_fail(-e.errno); } } function file_open(path, mode, k) { io_park_on(undefined, 0, k, () => file_open_with(io_bytes(path), mode), 0); } function file_open_bytes(path, mode, k) { io_park_on(undefined, 0, k, () => file_open_with(io_unlist(path), mode), 0); } io_eff(CID(File.open), file_open); io_eff(CID(File.open_bytes), file_open_bytes); - bend2/effs/file_read.js (2961 bytes)
// File // ==== // read(2) answers what is there, not what was asked: a pipe, a terminal // and a short read all stop before max. Fill the buffer or reach EOF, so // a caller that asked for n bytes gets n unless the file ends first; a // line stops after its '\n', read a byte at a time so nothing past it // leaves the file. An error after some bytes answers them (a pipe has // already given them up). Bun's readSync skips the syscall for 0 bytes, // so a 0-byte read goes through readvSync and fails on a bad handle as C // does; neither needs bun:ffi, which node lacks. // max is a cap, not a size: the buffer starts at what a regular file holds // past the given offset (one byte more, to see its end) or 64 KiB. It doubles // up to max as bytes arrive, so a read capped far above the available data // commits only what it reads (#1983). A line starts at 64 KiB whatever the file. function file_read_room(fs, file, len, line, offset) { let room = 65536; try { // A cap within room already determines the buffer size. const st = line || len <= room ? null : fs.fstatSync(file); if (st?.isFile()) { room = Math.max(room, st.size - (offset ?? 0) + 1); } } catch {} return Math.max(Math.min(len, room), 1); } function file_read_with(file, max, offset, pack, line = false) { const fs = require("fs"); const len = Math.min(max, 2147483647); let b = new Uint8Array(file_read_room(fs, file, len, line, offset)); let got = 0; do { if (got === b.length) { const c = new Uint8Array(Math.min(len, b.length * 2)); c.set(b); b = c; } const want = line && got < len ? 1 : Math.min(b.length, len) - got; let n; try { const at = offset === null ? null : offset + got; n = want === 0 ? fs.readvSync(file, [b.subarray(0, 0)], at) : fs.readSync(file, b, got, want, at); } catch (e) { // libuv retries EINTR for most calls, but not for read if (Math.abs(e.errno) === 4) { continue; } if (got === 0) { return io_tup(file, io_fail(Math.abs(e.errno ?? 5))); } break; } if (n === 0) { break; } got += n; } while (got < len && !(line && b[got - 1] === 10)); return io_tup(file, io_done(pack(b, got))); } function file_read(file, max, k) { io_park_on(undefined, 0, k, () => file_read_with(file, max, null, io_text), 0); } function file_read_line(file, max, k) { io_park_on(undefined, 0, k, () => file_read_with(file, max, null, io_text, true), 0); } function file_read_bytes(file, max, k) { io_park_on(undefined, 0, k, () => file_read_with(file, max, null, io_list), 0); } function file_read_at(file, offset, max, k) { io_park_on(undefined, 0, k, () => file_read_with(file, max, offset, io_list), 0); } io_eff(CID(File.read), file_read); io_eff(CID(File.read_line), file_read_line); io_eff(CID(File.read_bytes), file_read_bytes); io_eff(CID(File.read_at), file_read_at); - bend2/effs/file_size.js (832 bytes)
// File // ==== function file_size_now(file) { const fs = require("fs"); try { const size = fs.fstatSync(file).size; // the EOVERFLOW errno, 84 on mac and 75 elsewhere. io_sys().mac reads // the same platform, but io_sys() binds libc through bun:ffi, and on a // host without it that ask threw where the size was already read, so // the catch answered Fail on a good file. Nothing above this line // touches the FFI table, and nothing below it should either. const over = process.platform === "darwin" ? 84 : 75; return io_tup(file, size > 4294967295 ? io_fail(over) : io_done(size)); } catch (e) { return io_tup(file, io_fail(Math.abs(e.errno ?? 5))); } } function file_size(file, k) { io_park_on(undefined, 0, k, () => file_size_now(file), 0); } io_eff(CID(File.size), file_size); - bend2/effs/file_write.js (1693 bytes)
// File // ==== function file_write_buffer(file, b, offset = null) { const fs = require("fs"); let at = 0; try { while (at < b.length) { const n = fs.writeSync(file, b, at, b.length - at, offset === null ? null : offset + at); // no progress would retry forever (#1445) if (n === 0) { return io_tup(file, io_fail(5)); } at += n; } return io_tup(file, io_done({ $: CID(Unit) })); } catch (e) { return io_tup(file, io_fail(Math.abs(e.errno ?? 5))); } } function file_write(file, data, k) { io_park_on(undefined, 0, k, () => file_write_buffer(file, io_bytes(data)), 0); } function file_write_bytes(file, data, k) { const b = io_unlist(data); if (b === null) { return io_tup(file, io_fail(22)); } io_park_on(undefined, 0, k, () => file_write_buffer(file, b), 0); } // An fd can append without File.open's "a" (a shell's >> on stdout), so ask // the fd, as C does, after the handles File.open made with "a". A host // without bun:ffi (node) can't ask, and knows only those. function file_appends(file) { if (io_file_append.has(file)) { return true; } try { const sys = io_sys(); const flags = sys.fcntl(file, 3, 0); return flags >= 0 && (flags & (sys.mac ? 8 : 0x400)) !== 0; } catch (_) { return false; } } function file_write_at(file, offset, data, k) { const b = io_unlist(data); if (b === null || file_appends(file)) { return io_tup(file, io_fail(22)); } io_park_on(undefined, 0, k, () => file_write_buffer(file, b, offset), 0); } io_eff(CID(File.write_at), file_write_at); io_eff(CID(File.write), file_write); io_eff(CID(File.write_bytes), file_write_bytes); - bend2/effs/get_env.js (460 bytes)
// IO // == function io_get_env(name) { name = str_out(name); // Node cuts a name at a NUL; reject it like get_env.c (#1449). // Node's getenv may also read "A=B" as A's entry "A=B=C"; reject a "=" too. if (name.includes("\0") || name.includes("=")) return io_fail(2); const value = Object.hasOwn(process.env, name) ? process.env[name] : undefined; return value === undefined ? io_fail(2) : io_done(value); } io_eff(CID(IO.get_env), io_get_env); - bend2/effs/listener_close.js (164 bytes)
// Listener // ======== function listener_close(listener) { io_sys().close(listener); return { $: CID(Unit) }; } io_eff(CID(Listener.close), listener_close); - bend2/effs/now.js (105 bytes)
// IO // == function io_now() { return Math.floor(performance.now()); } io_eff(CID(IO.now), io_now); - bend2/effs/print_err.js (131 bytes)
// IO // == function io_print_err(text) { io_errs(text); return { $: CID(Unit) }; } io_eff(CID(IO.print_err), io_print_err); - bend2/effs/print.js (135 bytes)
// IO // == function io_print(text) { io_std(io_bytes(text + "\n")); return { $: CID(Unit) }; } io_eff(CID(IO.print), io_print); - bend2/effs/process_run.js (3992 bytes)
// Process // ======= const PROCESS_WORKER = ` // Eval workers may inherit module mode, where require is undefined. const { errno, signals } = process.getBuiltinModule("node:os").constants; const { parentPort } = process.getBuiltinModule("node:worker_threads"); const { spawn } = process.getBuiltinModule("node:child_process"); let port; let flag; parentPort.on("message", async (data) => { if (data.port !== undefined) { ({ port, flag } = data); return; } let got; try { got = await run(data); } catch (e) { got = { fail: errno[e] ?? (typeof e?.errno === "number" ? Math.abs(e.errno) : errno.EIO) }; } port.postMessage(got); Atomics.store(flag, 0, 1); Atomics.notify(flag, 0); }); function run({ argv, input, env, max, ms }) { return new Promise((yes, no) => { const proc = spawn(argv[0], argv.slice(1), { env, stdio: ["pipe", "pipe", "pipe"] }); // Node destroys proc.stdin at exit; a descendant may still read it. const stdin = proc.stdin; proc.stdin = null; const chunks = [[], []]; let size = 0; let error; const fail = (e) => { if (error !== undefined) return; error = e; proc.kill("SIGKILL"); stdin.destroy(); proc.stdout.destroy(); proc.stderr.destroy(); }; proc.once("error", fail); stdin.on("error", (e) => { if (e.code !== "EPIPE") fail(e); }); [proc.stdout, proc.stderr].forEach((stream, i) => { stream.on("error", fail); stream.on("data", (chunk) => { if (error !== undefined) return; size += chunk.length; if (size > max) fail("EFBIG"); else chunks[i].push(chunk); }); }); // Feed stdin until the child exits and its stdout and stderr close. let live = 3; const done = () => --live || stdin.destroy(); proc.once("exit", done); proc.stdout.once("close", done); proc.stderr.once("close", done); const timer = setTimeout(() => fail("ETIMEDOUT"), Math.min(ms, 2 ** 31 - 1)); proc.once("close", (code, signal) => { clearTimeout(timer); if (error !== undefined) no(error); else yes({ code: code ?? 128 + (signals[signal] ?? 0), out: Buffer.concat(chunks[0]).toString("utf8"), err: Buffer.concat(chunks[1]).toString("utf8") }); }); stdin.end(input); }); } `; let process_worker = null; function process_run_now(program, args, input, maxOutput, timeoutMs) { const argv = [str_out(program)]; for (let xs = args; xs.$ === CID(Con); xs = xs.tail) { argv.push(str_out(xs.head)); } if (maxOutput === 0 || timeoutMs === 0 || argv.some((arg) => arg.includes("\0"))) { return io_fail(22); } if (argv[0] === "") { // spawn("") throws with no errno; C's posix_spawnp("") answers ENOENT. return io_fail(2); } if (process_worker === null) { const { Worker, MessageChannel, receiveMessageOnPort } = require("node:worker_threads"); const { port1, port2 } = new MessageChannel(); const flag = new Int32Array(new SharedArrayBuffer(4)); const worker = new Worker(PROCESS_WORKER, { eval: true }); worker.unref(); worker.postMessage({ port: port2, flag }, [port2]); process_worker = { worker, port: port1, flag, receive: receiveMessageOnPort }; } const { worker, port, flag, receive } = process_worker; Atomics.store(flag, 0, 0); worker.postMessage({ argv, input: io_bytes(input), env: { ...process.env }, max: maxOutput, ms: timeoutMs }); if (Atomics.wait(flag, 0, 0, timeoutMs + 1000) === "timed-out") { worker.terminate(); process_worker = null; return io_fail(5); } const got = receive(port).message; return got.fail !== undefined ? io_fail(got.fail) : io_done(io_tup(got.code, got.out, got.err)); } function process_run(program, args, input, maxOutput, timeoutMs, k) { io_park_on(undefined, 0, k, () => process_run_now(program, args, input, maxOutput, timeoutMs), 0); } io_eff(CID(Process.run), process_run); - bend2/effs/random_u32.js (581 bytes)
// IO // == // WebCrypto answers Fail by throwing, and a host without it throws a // ReferenceError on the name, so the declared Result is what a program // that handles Fail already expects here. The C lane gets the errno out // of getrandom; WebCrypto carries no errno on any host, so EIO stands in // and io_fail(5) says what process_run.js already says when Bun throws // without one. function io_random_u32() { try { return io_done(crypto.getRandomValues(new Uint32Array(1))[0]); } catch (_) { return io_fail(5); } } io_eff(CID(IO.random_u32), io_random_u32); - bend2/effs/sleep.js (214 bytes)
// IO // == // Parks until ms milliseconds from now. function io_sleep(ms, k) { io_park_on(undefined, false, k, () => ({ $: CID(Unit) }), performance.now() + Number(ms)); } io_eff(CID(IO.sleep), io_sleep); - bend2/effs/socket_close.js (150 bytes)
// Socket // ====== function socket_close(socket) { io_sys().close(socket); return { $: CID(Unit) }; } io_eff(CID(Socket.close), socket_close); - bend2/effs/spawn.js (160 bytes)
// IO // == function io_spawn(act) { io_push(act, (x) => ({ $: CID(Emit), value: x }), true); return { $: CID(Unit) }; } io_eff(CID(IO.spawn), io_spawn); - bend2/effs/tcp_accept.js (1520 bytes)
// TCP // === // The request parks until the listener is readable, so a backlog never // keeps the loop from its timers; an accept that still finds no connection // (the listener is non-blocking) parks again. The accepted socket is // non-blocking for life. function tcp_accept_with(listener, k, at) { const sys = io_sys(); const lfd = listener; const intr = 4; const go = () => { let fd = sys.accept(lfd, null, null); while (fd < 0 && sys.errno() === intr) { fd = sys.accept(lfd, null, null); } if (fd < 0) { const code = sys.errno(); if (code !== (sys.mac ? 35 : 11)) { return io_tup(listener, io_ready(at, io_fail(code))); } if (io_late(at)) { return io_tup(listener, { $: CID(Wait), rest: { $: CID(Unit) } }); } io_park_on(lfd, false, k, go, at); return undefined; } if (sys.fcntl(fd, 4, sys.fcntl(fd, 3, 0) | (sys.mac ? 4 : 0x800)) < 0) { const code = sys.errno(); sys.close(fd); return io_tup(listener, io_ready(at, io_fail(code))); } return io_tup(listener, io_ready(at, io_done(fd))); }; io_park_on(lfd, false, k, go, at); return undefined; } function tcp_accept(listener, k) { return tcp_accept_with(listener, k); } // try_ passes a deadline at: past it, an accept that would wait answers Wait{}. function tcp_try_accept(listener, ms, k) { return tcp_accept_with(listener, k, io_until(ms)); } io_eff(CID(TCP.accept), tcp_accept); io_eff(CID(TCP.try_accept), tcp_try_accept); - bend2/effs/tcp_connect.js (1260 bytes)
// TCP // === // The socket is non-blocking for life: EINPROGRESS parks the computation // until the socket is writable, and then SO_ERROR says how the connect ended. function tcp_connect(host, port, k) { const at = io_addr(host, Number(port)); if (at === null) { return io_fail(22); } const sys = io_sys(); const fd = sys.socket(2, 1, 0); if (fd < 0) { return io_fail(sys.errno()); } const end = (code) => { if (code !== 0) { sys.close(fd); return io_fail(code); } return io_done(fd); }; const error = () => { const v = new Int32Array([0]); const l = new Uint32Array([4]); return sys.getsockopt(fd, sys.mac ? 0xffff : 1, sys.mac ? 0x1007 : 4, sys.ptr(v), sys.ptr(l)) < 0 ? sys.errno() : v[0]; }; const set = sys.fcntl(fd, 4, sys.fcntl(fd, 3, 0) | (sys.mac ? 4 : 0x800)); const ok = set >= 0 && sys.connect(fd, sys.ptr(at), 16) >= 0; const code = ok ? 0 : sys.errno(); // An interrupted connect (EINTR, 4) goes on in the background, so it is // waited on as EINPROGRESS is. if (code !== (sys.mac ? 36 : 115) && !(set >= 0 && code === 4)) { return end(code); } io_park_on(fd, true, k, () => end(error())); return undefined; } io_eff(CID(TCP.connect), tcp_connect); - bend2/effs/tcp_listen.js (671 bytes)
// TCP // === function tcp_listen(host, port) { const at = io_addr(host, Number(port)); if (at === null) { return io_fail(22); } const sys = io_sys(); const fd = sys.socket(2, 1, 0); if (fd < 0) { return io_fail(sys.errno()); } const one = new Int32Array([1]); const level = sys.mac ? 0xffff : 1; sys.setsockopt(fd, level, sys.mac ? 4 : 2, sys.ptr(one), 4); if (sys.bind(fd, sys.ptr(at), 16) < 0 || sys.listen(fd, 512) < 0 || sys.fcntl(fd, 4, sys.fcntl(fd, 3, 0) | (sys.mac ? 4 : 0x800)) < 0) { const code = sys.errno(); sys.close(fd); return io_fail(code); } return io_done(fd); } io_eff(CID(TCP.listen), tcp_listen); - bend2/effs/tcp_recv.js (1993 bytes)
// TCP // === // A recv that finds nothing (the socket is non-blocking) parks until the // socket is readable. What it finds, read makes a String (io_text) or a // List of bytes (io_list). // max is a cap, not a size: one recv answers at most 64 KiB, as a short // read may, so a recv capped far above what arrived commits only 64 KiB // (File.read's twin, #1983). function tcp_recv_with(socket, max, k, read, at) { if (Number(max) === 0) { return io_tup(socket, io_ready(at, io_fail(22))); } const sys = io_sys(); const fd = socket; const b = new Uint8Array(Math.min(Number(max), 65536)); const again = sys.mac ? 35 : 11; const intr = 4; const go = () => { let n = Number(sys.recv(fd, sys.ptr(b), b.length, 0)); while (n < 0 && sys.errno() === intr) { n = Number(sys.recv(fd, sys.ptr(b), b.length, 0)); } if (n < 0) { const code = sys.errno(); if (code !== again) { return io_tup(socket, io_ready(at, io_fail(code))); } if (io_late(at)) { return io_tup(socket, { $: CID(Wait), rest: { $: CID(Unit) } }); } io_park_on(fd, false, k, go, at); return undefined; } const got = n === 0 ? { $: CID(None) } : { $: CID(Some), value: read(b, n) }; return io_tup(socket, io_ready(at, io_done(got))); }; return go(); } function tcp_recv(socket, max, k) { return tcp_recv_with(socket, max, k, io_text); } function tcp_recv_bytes(socket, max, k) { return tcp_recv_with(socket, max, k, io_list); } // The try_ twins pass a deadline at: past it, a recv that would wait is Wait{}. function tcp_try_recv(socket, max, ms, k) { return tcp_recv_with(socket, max, k, io_text, io_until(ms)); } function tcp_try_recv_bytes(socket, max, ms, k) { return tcp_recv_with(socket, max, k, io_list, io_until(ms)); } io_eff(CID(TCP.recv), tcp_recv); io_eff(CID(TCP.recv_bytes), tcp_recv_bytes); io_eff(CID(TCP.try_recv), tcp_try_recv); io_eff(CID(TCP.try_recv_bytes), tcp_try_recv_bytes); - CHANGELOG.md (56061 bytes)
# Changelog Each release names what changed for a user. `bend update` installs the latest one; the GitHub release carries the same notes. ## 2.0.40 (2026-11-05) - **The checker no longer hangs on a proof that a list is its own head <> tail**: conversion gave a share cell the value of an equal one, so a bare `{==}` of `{Hd(D) <> Tl(D) == D}` made `D` name itself, and the next check through `D` never ended, or `--verdict` overflowed the stack. Equal cells now join a class and no value moves: a file that ran past 900 s checks in 3.3 s. - **`bend --publish` sends the `README.md` beside the entry**, and the hub shows it (PR #2033). - **`bend-cache`** (`tools/`): a proof cache for `--check-only` outside bend (PR #2045). - **Base**: `Array.get_unchecked`, an `@unsafe` read without the wrap mask (PR #1880 by adeerkhan); `U32.popcount` and `U32.ctz` (PR #1905 by MattCozendey); merge sort starts from sorted pairs (PR #2018 by toprameen). - **IO**: positioned byte writes (PR #1887 by vicmcorrea); `File.open(path, "r+")` opens an existing file to read and write (PR #1853 by EpsilonPhoenix); a pointer event is one `Press` for a mouse, a finger or a pen (PR #1867 by MattCozendey); native fullscreen keeps the logical rendering resolution (PR #1443 by oxura). - **Faster checks**: let kind checks, quantity comparisons, the scope search, call arguments, constructor fields, `pmap_set`, free names, operators and the verdict's walk each do less work (PRs #1947, #1952 by raramos9; #1965, #1967 by sebastianbreguel; #1966, #2013, #2048, #2053, #2060, #2061 by nicolas-abril). - **Faster programs**: a long loop over `F32` is a call on the host too: nbody 1.19x on SEQ, 1.15x on PAR (#1240, PRs #1814, #1950 by nicolas-abril); a match arm's node allocation is hoisted (PR #1792 by viridale); host lanes share large freed blocks (PR #1869 by sebastian-griego); `blk_new` fills vectorize (PRs #1928 by raramos9, #1946 by nicolas-abril); a wide def's boxed record stays boxed until a use needs it, and an unfold builds its callee's body once (PRs #2036, #2051 by nicolas-abril); JS channel waits, GPU size checks and positioned reads cost less (PRs #1859, #1872 by sebastianbreguel; #1993, #2015, #2016 by toprameen). - **Clearer errors** (#1632): a call missing arguments, a pair where `Data` is expected, a self-call that does not shrink, a false `{==}` (its sides as written), a match missing cases and a def given `<...>` each say what is wrong (PRs #1865, #2000, #2002, #2006, #2007, #2008); a do-block bind or let written without its type gets a note (PR #1807 by HamedShams); a call to a def written below its caller names the file order (#1782, PR #1783 by viridale); a stray `=` after a do block's last statement is refused (PR #1889); spaced successor patterns and a glued `x+y` point at the right spelling (PR #1969); the import path and array depth errors say what a name and `d` are (PRs #1963, #1964 by sebastianbreguel). - **CLI**: a BUILD tag after the version, for forks (PR #1907 by MattCozendey); a `!` program built for the CPU because no CUDA toolkit was found says so (PR #1888); colliding output requests are refused before anything is written (PR #2010 by vicmcorrea); a hyphenated published file prints valid aliases (PR #1849 by vicmcorrea). - **Fixes**: - Checker and verdict: a law names its module's own def when a Base constructor shares the name (#1236, PR #2047 by nicolas-abril); `!=` and `where` mean the `Empty` and `Exists` of the file they are written in (PR #1577 by HamedShams); BendTT labels spell the canonical key injectively (#1131, #1247, PR #1216 by oxura); `--verdict` keeps dependent template argument types and uses checked defs as model fallbacks (PRs #1874, #1901 by sebastian-griego); a term at a type with no finite η-long form goes to the kernel whole (#1164, PR #1896 by nicolas-abril); `Nat` converts to `F32` without narrowing to `U32` (PR #1610 by oxura). - Compiler: a fold reads an argument's liveness by its position (PR #2054 by nicolas-abril); a fork's join opens on the fork path's holds (#1953, PR #2042); on Metal the shared-node half of a take is a call (PR #1978 by HamedShams); CUDA's dispatch entry check reads the frontier from device memory (PR #1877 by nuxyel); `Window.open` without `Window.frame` builds natively (PR #1883 by sebastianbreguel); C comments keep Unicode separators (PR #1972 by toprameen); process workers run in module mode (PR #1842 by toprameen). - IO: TCP connect, accept, send and receive, UDP send and receive, and native file opens and writes retry after an interruption instead of failing (PRs #1909, #1910, #1911, #1912 by sebastianbreguel, #1878 by EpsilonPhoenix, #1900 by toprameen, #1862, #1898 by sebastian-griego); `File.read` fills its buffer (PR #1845 by adeerkhan), its `max` is a cap on JS (#1983, PR #1985 by lukaszsamson) and it reads through fs on Node (PR #1881 by sebastianbreguel); an interrupted `File.read_line` no longer reads a byte before its buffer (PR #1918 by sebastianbreguel); `Process.run` refuses a file with no `#!` line on macOS, and answers `ENOENT` for an empty program on JS (PRs #1860, #1875 by sebastianbreguel); `File.write_at` refuses an `O_APPEND` fd on Bun (PR #1903 by lee-eojin); `Window.open` refuses a bad size or a NUL title on JS (PR #1884 by sebastianbreguel); macOS window titles decode as UTF-8 (PR #1834 by sebastian-griego); JS channels release timed-out and abandoned waiters (PRs #1879 by toprameen, #1976 by EpsilonPhoenix), and their buffer drains from a ring (PR #1851 by Revaycolizer); JS timer waits work without Bun FFI (PR #1996 by EpsilonPhoenix); `io_wait` flushes stdout after JS File and Process effects (PR #1899 by nicolas-abril); UDP send addresses are checked before FFI setup (PR #1974 by sebastian-griego); `TCP.recv` past `INT32_MAX` caps the read on JS as on C (PR #1861 by sebastianbreguel); the wake pipe is set up before it goes nonblocking (PR #1935 by betterclever). - Tools: the formatter keeps raw apostrophe literals whole (PR #1971 by toprameen); a bundle encodes quoted HTML filenames (PR #1977 by EpsilonPhoenix). - **Docs**: the `Text` constructor collision (PR #1933 by oxura); each lane's clock zero, and `File.read_line` with max 0 (PR #1882 by sebastianbreguel). ## 2.0.39 (2026-10-23) - **`bend --publish` sends only files inside the entry's directory**: a `../` climb, a symlink out of it or a `LICENSE` that links out is refused before mining, with no hub request (#1836, PR #1838 by oxura). - **`File.open(path, "x")`** creates a new file and fails with `EEXIST` if the path exists, in one step (#1821, PR #1824). - **Non-UTF-8 arguments**: `IO.args_bytes` gives each argument's bytes, and `File.open_bytes` opens a path given as bytes (#1798, PR #1799 by viridale). - **`Process.run` runs through one worker on Bun and Node**, so it no longer ends the run on Node, and a child that leaves stdin unread no longer hangs it (#1468, PR #1831 by oxura). - **Metal: the lane spill of 2.0.38 is gone** (PR #1809): it made `bend -o` of a `!` program build 17% slower. A full lane fails with `ERR_DEEP` again, as in 2.0.37. - **Fixes**: - The GPU build sees a closure in a later instance of the same datatype (#1513, PR #1542). - C: a read-only walk borrows its list when a sum type puts a word where another constructor has a box (#1805, PR #1806 by viridale); a memory fault ends the program by its signal (SIGSEGV, SIGBUS), not exit 1, after flushing output (PR #1828 by oxura). - `IO.get_env` refuses a name with a `=`, which read part of another variable on C and Node (#1794, PR #1795 by orezraey). - **CLI**: `bend -o` never overwrites an input through a hard link or with the GPU archive `<out>.gpu` (PRs #1797 by sebastian-griego and #1826 by toprameen); a `$CC` that is not a usable clang 14+ ends the build with its reason, instead of a silent plain-clang build (#1802, PR #1804 by Yi-111-a). - **Tools**: the formatter keeps body columns after `(`, `;`, tuple commas and in nested lambdas, and keeps a generic's `>` apart from a following `=` (PRs #1803 by toprameen, #1811, #1816, #1833, #1839 by vicmcorrea). - **Docs**: BendTT proves adequacy, a checked law holds at each closed instance (PR #1627 by ScottMoore0); the guide and BendRT say a hot type counts the fields of every node, shared or not (#1559, PRs #1812 by vicmcorrea and #1813), and BendRT matches the runtime on the corpus, JS requests and the CUDA cube (#1822, PR #1823). ## 2.0.38 (2026-10-20) - **A compiled program's runtime options go between `+RTS` and `-RTS`** (#1466, PR #1530 by viridale). **Breaking:** `./main --threads 4` now passes `--threads 4` to the program (`IO.args`); write `./main +RTS --threads 4 -RTS`. A trailing `-RTS` may be left off, `BENDRTS` holds options too (the command line wins), `--` stops option reading and reaches the program, and an unknown option inside the bracket is an error. `--threads` takes digits, `--gpu` takes `on`, `off` or a size in `GB` or `MB`. - **JS modules keep their names apart.** **Breaking for JS hosts:** a constructor's JS tag is its name in the file that declares it, so a value crosses modules and matches the right arm (#1105, PR #1488 by oxura); imported export keys and foreign JS def ids keep their `:` (#1758, #1759, #1766, PR #1760 by oxura). - **`TCP.send` and `TCP.try_send` hand back unsent bytes**, a `List<&2, U32>` to resume with `TCP.send_bytes`, so a write cut inside a UTF-8 character loses nothing (#1764, PR #1765 by oxura). **Breaking** for code that read the residue as a String. - **Native windows emit `Text` events** with the typed characters on Linux and macOS (#1019, PR #1441 by oxura). **Breaking:** Base's `Event` now declares the bare constructor name `Text`. A program importing Base cannot also declare its own `Text` constructor; rename it, for example to `NodeText` (#1913). - **A `Char` holds any u32 on every lane**; a non-scalar becomes U+FFFD only where text leaves Bend (#1080, PR #1411 by oxura). - **`--verdict`**: - The verdict says why each def it lists relies on unsafe or foreign code (PR #1531 by MattCozendey), and hints when those defs come only through unused imports (#1463, PR #1558). - A def specialized at a finite `~` parameter is checked by the kernel over each value, so an empty type no longer passes unchecked (#1186, PR #1225 by nicolas-abril); a `~` constant takes its model from the template's instances (PR #1580 by nicolas-abril). - The kernel accepts a self-call on a constructor rebuilt around a smaller part of its input, as the checker does (#1167, PR #1200 by nicolas-abril). - Fixes: annotations under η and let inlining (#1665, #1669, PR #1666 by aaaxn); a bare constructor in a type (#1619, PR #1620 by ScottMoore0); shared group prefixes (PR #1704 by sebastian-griego); kernel failures show their details (#1535, PR #1536 by viridale). - **Faster**: - A GPU bang chains its rounds on the device, three command buffers in flight, with no host round trip per stage (PR #1447 by nicolas-abril). - A flat generic def's spin takes words at its instance's layouts (#1195, PR #1588). - `String.order` walks both strings once: 8x on C, and `String.eq` of long strings no longer overflows the JS lane (PR #1459 by aldeni); `String.contains` is linear on JS (PR #1628 by sebastian-griego). - Emission allocates 40% less on large files (PR #1617 by nicolas-abril); word matches with many literals compile faster (PR #1387 by Iann29). - `U32.pow` by squaring and `F32.show` without a second conversion on C (PRs #1567 and #1591 by sebastian-griego); `F32.read` rejects bad input in linear time (PR #1625 by toprameen); expired channel waiters leave in constant time (PR #1671 by sebastian-griego). - CUDA keeps its L1 cache in `bend_dev` (PR #1602 by wakamex). - **Fixes**: - Metal: a full lane stack spills to the heap, so non-tail recursion under `!` no longer faults at 1023 frames (#1393, #1394, PR #1439 by totaland). - C: a shared word is written back to its fork frame slot (PR #1615 by viridale); a recursive spine is freed cell by cell (#1307, PR #1438 by oxura); native channels free their rows and unread values (#1268, PR #1532 by oxura); Nat powers and bit widths take checked paths (#1709, #1710, PR #1713 by oxura); functions only an effect calls stay reachable (#1711, #1712, PR #1714 by oxura); the crash trap is async-signal-safe (PR #1655 by adeerkhan). - IO: ready effects yield to other computations every 64 (#1719, PR #1723 by oxura); `IO.exit` flushes buffered output (PR #1519 by vicmcorrea); file and JS stream writes fail on zero progress (#1445, PRs #1446 by oxura and #1747 by vicmcorrea); nested JS IO schedulers are isolated and resume their own channel waiters (#1524, #1761, #1770, PRs #1525 and #1762 by oxura); UDP receive buffers are bounded (#1695, PR #1698 by oxura); `TCP.connect` checks its arguments on JS (PR #1618 by vicmcorrea); JS `Audio.write` counts whole frames and paces on monotonic time (PRs #1683 by toprameen and #1597 by vicmcorrea). - Base: `List.any`, `all`, `contains` and `find` stop once the answer is known (#1726-#1729, PR #1730 by oxura); prefix checks stop at the prefix (#1640, PR #1645 by EpsilonPhoenix); `F32.round` keeps negative zero and rounds once (#1611, PRs #1613 by oxura and #1547 by vicmcorrea); `F32.lerp` stays finite and keeps its endpoints (#1607, #1749, PRs #1608 and #1754 by oxura); `F32.to_nat` keeps wide values (#1636, PR #1642 by oxura); JS `U32.to_f32` keeps zero positive and scalar F32 host inputs are rounded (#1692, #1568, PRs #1693 and #1569 by oxura). - Effects: `CID`/`FID` are scanned with the source's own comment rules (#1604, PR #1653 by adeerkhan); a bad Nat from a JS host says its range (#1634, PR #1656 by oxura). - **CLI**: - `bend page.html -o <dir>` never overwrites its own page (PR #1690 by toprameen); inline HTML modules stay apart from real assets and from each other (#1752, #1753, #1767, PRs #1756 and #1768 by oxura); decoded module paths are classified right (#1570, PR #1571 by oxura). - Output finishes after short writes to a pipe (PR #1691 by toprameen); a failed update check keeps the command's status (PR #1603 by vicmcorrea); filtered Base output keeps `@unsafe` (PR #1538 by toprameen). - **Tools**: the formatter keeps column-pinned blocks, nested match arms, inline bodies and mixed line endings (PRs #1302 by dearlordylord, #1755, #1672 by oxura, #1583, #1584, #1590, #1757 by vicmcorrea and - INSTRUCTIONS.md (531 bytes)
You are the autonomous runtime coordinator for bend. System Archetype: tool. Description: Bend 2: a fast language that blocks AI mistakes via proof. Install: curl -fsSL https://bend-lang.com/install.sh | sh Core Directives: 1. Execute operations deterministically following verified repository manifests. 2. Strictly enforce safe input validation and local-first execution boundaries. 3. Provide structured outputs, formatted logs, and actionable resolution steps. 4. Preserve data integrity and respect local workspace isolation.
- LICENSE (11344 bytes)
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2026 HigherOrderCO Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - README.md (11085 bytes)
<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="media/hero_dark.gif"><img src="media/hero.gif" width="560" alt="Bend: a fast language that blocks AI mistakes via proof"></picture></p> In the post-AGI economy, humans will eventually stop writing and reading code, but we still need an ambiguity-free language to communicate our intents to the AIs building the world around us. Bend is that language. With **laws**, intents can be more precise than natural language. With **proofs**, we can mechanically verify the AI implemented our prompts correctly. And with a **fast compiler**, we can run that code at peak compute. That's Bend - and nothing else. ## Bend runs FAST **Target:** be as fast as C on the CPU, as fast as CUDA on the GPU. **Status:** <p align="center"><img src="media/runtime.gif" width="640" alt="Runtime benchmarks: Bend vs C, TypeScript, Lean, on 1 core, 16 cores and the GPU"></p> Thanks to strong types, purity and linearity, Bend compiles to fast executables as fast as hand-written C (single-core), and even faster (on 10000s cores). The entire language runs on the GPU, with full memory unification. ## Bend checks FAST **Target:** outperform every proof assistant by several OOMs. **Status:** <p align="center"><img src="media/checker.gif" width="640" alt="Checker benchmarks: Bend vs Isabelle, Agda, Lean, Rocq"></p> Bend's compiler is so powerful it can verify mathematical proofs. Usually, this is slow. Bend is not. It checks, in under a second, files that other projects would take minutes, making proofs way more practical. ## Bend is PARALLEL No threads, no locks, no kernels to write. Split the work in two, and Bend spreads the calls over every core it can find, then joins them back. Below, `pow2(20)` divides until one task sits on each of 4,096 GPU cores: <p align="center"><img src="media/parallel.gif" width="440" alt="pow2 splitting over 4,096 GPU cores, then folding back"></p> ## Bend BLOCKS mistakes - with proof PROBLEM: How can you **trust** AI code, without reading it? SOLUTION: By forcing your AI to write a **correctness proof**. Bend introduces `LAWS.bend`, a file where you declare rules that your app must not break. Bend's compiler then **guarantees** that these laws always hold, by demanding **mathematical proof** whenever your code is edited. For example, consider a game with one law: *winning is impossible*. Here's how it plays out: <p align="center"><b>Law</b>: winning is <b>impossible</b><br><img src="media/game_law.gif" width="480" alt="The player walks up and bumps the wall of the flag's room"><br><i>So far, it works!</i></p> <p align="center"><b>New feature:</b> "Claude, make the board wrap around"</p> <p align="center"><b>Without LAWS.bend:</b><br><img src="media/game_bug.gif" width="480" alt="The player wraps around the edge and takes the flag"><br><i>Laws broken. AI mistake: <b>merged</b>.</i></p> <p align="center"><b>With LAWS.bend:</b><br><img src="media/game_law_kept.gif" width="480" alt="A wall on the far edge stops the player"><br><i>Laws intact. AI mistake: <b>blocked</b>!</i></p> Without `LAWS.bend`, a bug was merged. With it, the AI had to retry, until no bugs were left! In this case, it added a wall, but it could have moved the flag, made the room kill you, or whatever. The only thing it can't do is commit a bug, because it is **mathematically impossible** to break laws in `LAWS.bend`. The compiler *enforces* it. Using `LAWS.bend` is simple. 1. Ask your AI to formalize your app's rules in `LAWS.bend`. Example: - LAW: *"the sum of all balances must be zero"* - LAW: *"players can never pass through solid walls"* - LAW: *"list_sort() must always return ascending numbers"* - LAW: *"array_set() may never be called out-of-bounds"* - LAW: *"winning is impossible"* (the demo above!) - And so on. Anything you can spell can become a law. 2. Ask your AI to run `bend PROOF.bend` after editing any code. 3. That's it. Rejoice as your app never again breaks or violates your rules. You can also edit `LAWS.bend` yourself. Here's how it looks: ```python # LAWS.bend law you_cant_win: # "winning is impossible" for moves: List<Game.Move> # any sequence of moves board = Game.replay(Game.start(), moves) # replayed from the start {Game.is_won(board) == False{} : Bool} # never leads to victory ``` ```python # PROOF.bend def Laws.you_cant_win(moves): # ... written by the AI ``` In short, `LAWS.bend` is `AGENTS.md` backed by **proof**. With `LAWS.bend`, *"make no mistakes"* becomes enforceable. [Skeptical? Edit the demo's code and break the "you can't win" law!](https://bend-lang.com/#lab) # Get Started ### 1. Install: ```bash curl -fsSL https://bend-lang.com/install.sh | sh ``` This `bend` ignores a project's `bunfig.toml` and `.env`; `bun bend2/main.ts` from a checkout reads them, so check untrusted code with `bend`. ### 2. Tell your agent to use Bend: Add this to your `AGENTS.md`: ``` When using Bend: - run `bend guide` to learn it - use `LAWS.bend` to keep important rules - run `bend PROOF.bend` before committing - parallelize the code whenever possible ``` Then, just say: "use Bend"! ### 3. Enjoy bug-free, fast vibe-coded apps! Hints: - Ask it to write laws for anything that can't break. - Ask it to parallelize anything you want to be fast. - Bend is young. If anything goes wrong, ask it to open an issue. <3 Bend works best on the back-end, on Linux or macOS. # Examples ### Syntax == Python + dependent types ```python import Base # Performs effects on the CPU. def main() -> IO(Unit): do IO<Unit>: name : String <- IO.try(String, IO.get_env("USER")) IO.print("Hello, " ++ name) ``` ### Parallelism == divide-and-conquer ```python import Base # Computes 2^d in parallel: a tree of d levels, one leaf per unit. def pow2(+d: Nat) -> U32: match d: case 0n: 1 case 1n+p: a b = pow2(p) pow2(p) (a + b : U32) # Runs pow2 on the GPU, via `!`. def main() -> IO(Unit): result = pow2!(20n) IO.print(U32.show(result)) ``` ### Theorems == laws, Proofs == defs ```python import Base # CLAIM: for every nat x, x + 0 equals x. law add_zero: for x: Nat {Nat.add(x, 0n) == x : Nat} # PROOF: induction on `x`, one rewrite (`%`) per step. def add_zero(x): match x: case 0n: {==} case 1n+xp: %add_zero(xp) : {1n+Nat.add(xp, 0n) == 1n+_ : Nat} {==} ``` # References - Guide: [GUIDE.md](guide/GUIDE.md), also printed by `bend guide`. - Demos: [demos/](demos), apps, servers and proofs, each with its `LAWS.bend`. - Base: [base.bend](bend2/base.bend), the base library, also printed by `bend base`. - Paper: [BendTT: An Affine Dependent Type Theory](paper/BendTT.pdf). - Paper: [BendRT: A Parallel Runtime for CPUs and GPUs](paper/BendRT.pdf). - Formalization: [bendtt.lean](bend2/bendtt.lean), the kernel of `--verdict` and its proofs, in Lean. - Benches: [bench/](bench), every bench used to make the charts above. - Formatter: [bend-fmt-lsp](tools/bend-fmt-lsp), a formatting-only Bend 2 language server. - Community language server: [bend2-lsp](https://github.com/don2e4/bend2-lsp), with formatting, diagnostics, and hover. - Community workshop: [Bend 2 pocket workshop](https://np.github.io/bend-workshop/), the checker and JS compiler in one HTML page, with goals and proof tools, phone first. # Community - Website: https://bend-lang.com - Discord: https://discord.bend-lang.com - Twitter/X: https://x.com/bendlang - Reddit: https://www.reddit.com/r/bendlang/ - Issues: https://github.com/bendlang/bend/issues # Limitations ``` - Bend 2 is a new language. Bend 1 programs and HVM do not carry over. - Everything is annotated and nothing is inferred, so code is verbose. - No type classes, no traits, and no macros beyond compile-time templates. - Bend has no tactics or proof search; proving theorems takes extra effort. - Values are affine: closures and arrays cannot be shared. - Recursion must terminate; `@unsafe` or `def f?(..)` turns the check off. - Computed matches (`match f(x)`) aren't supported. Must split it manually. - There is no syntax for if-then-else: a branch is a match on True and False. - Numbers are Nat, U32 and F32 only: no U64, I64 or F64 (Metal has no f64). - F32 is axiomatic: nothing about floating point can be proven. - Strings are linked lists of characters, so text processing is slow. - Base is small: expect to write helpers other languages ship built in. - Effects are few: print, env, time, sleep, spawn, channels, files, TCP, UDP. UDP buffers fit IPv4's 65,507-byte payload limit. - No TLS, HTTP library, JSON or regex for now (you can add them as foreigns). - Targets are C, Metal, CUDA and JavaScript; Lua, Luau and Python are planned. - The JavaScript target runs on one core and has no graphics or audio. - Parallelism requires balanced calls. Flexible parallelism will be added later. - Atomic arrays shared across threads are experimental and need `@unsafe`. - One GPU per program, one event loop, and no multi-machine execution yet. - One C file per program: no separate compilation, no incremental builds. - Compiling to native is slow (clang/CUDA/Metal). For fast development, use JS. - The compiler is young and has blind spots (unusually slow programs). Report. - We don't have as many benchmarks as we'd like yet, especially for the checker. - The compiler (not kernel) is 99% AI-written and not yet fully audited. - The checker has no proof and may have bugs; `--verdict` uses a proven kernel. - Laws are proven about Bend's semantics. The backends can still differ, for example in F32 NaN. See WONTFIX. - `--verdict` checks the translated terms, the parser and translation into the kernel are not proven. - A binary needs clang 14+; ! needs 19+, Metal or CUDA 12. - No Windows (WSL works); on Linux, Window and Audio need X11 and ALSA headers. - A hub package is a hash, unless its author names and versions it after `bend login`. - Error messages are terse; no debugger, profiler or REPL. - The editor tool only formats; the community bend2-lsp adds errors and hover. - No test framework and no documentation beyond the guide. - And more that escape me. Be patient, report bugs and request features! Most of these limitations are being addressed and will improve over time! ``` **BEND IS YOUNG. EXPECT BUGS AND [REPORT THEM](https://github.com/bendlang/bend/issues).** # Credits Bend is created by [Victor Taelin](https://github.com/VictorTaelin) and built by the team: - [Lorenzo W Battistela](https://github.com/Lorenzobattistela) - [Paulo J Cavalcanti](https://github.com/pjcavalcanti) - [Nico Abril](https://github.com/nicolas-abril) - [Vanessa Ostroski](https://github.com/Ostrowskii) - [Vitor Chiarelli Neves](https://github.com/Sipher) - [Alex Van de Sande](https://x.com/avsa) If you were part of this and your name is missing, please get in touch so we can add it here. Thanks to [Ayush Somani](https://ayushsomani.me/) for reserving the `bend-lang` name for us. - WONTFIX.txt (6957 bytes)
WONTFIX: what Bend will not fix, and why. Each entry is a design choice, a limit of our team size, or an open problem with no solution we trust yet. Read this file before you open an issue. DESIGN (intentional choices) `bend file.bend` runs a pure main lazily; compiled lanes are strict (#775) The checker skips an unused argument; a binary evaluates it. Same value, different cost. The checker skips dead code (#820, #878, #973, #1091) In `(y => x)(e)`, `e` is dead: a comment, invisible to the theory, with no runtime effect. A match arm an earlier arm shadows, or a fallback past a type's last constructor, wins no leaf and is dead the same way. The checker visits neither. This makes the check faster and costs no correctness: the term it checks is the term it runs. A written redex reduces as it is read, so `(x => x(x))(x => x(x))` never ends (#973). `~` template arguments are compile-time (#784) A `~` argument must be closed. A def parameter is a runtime value, so it cannot fill one. Pass the function as a plain argument instead. Allocation failure fail-stops the runtime (#792) Out of memory is fatal everywhere, not a `Fail`. A program bounds the `max` it passes to a receive effect; the runtime only caps it at INT32_MAX. The C compiler is clang only (#773) The C output uses `#embed` and clang pragmas. gcc is not a target. The termination check reads arguments left to right (#770) An argument before the decreasing one must pass through unchanged. Put the decreasing argument first. No common-subexpression elimination (#812) Two calls of `f(p)` run twice. Bind the value once. The checker is not optimal: some terms are exponential or overflow (#993, #1075) bend.ts is not beta-optimal and recurses on the machine stack. No checker avoids every case: `F(100000 * 2) == F(100000 + 100000)` unrolls fully, since the sides differ. So conversion takes no layer that makes equality quadratic (an identity pass before each reduction) or every check slower by a constant (hash-consing, a memo of seen terms): each layer covers one more family and slows every proof. Fix the representation instead: a def opens a value before it copies it (as U32.max does), and a law keeps its large constants and depths abstract. Do not open an issue per exponential or overflow. A fallback arm does not refine a dependent goal (#1091) In `case rest:` the scrutinee stays a variable. Write the constructor arms. `!` goes to the GPU only at the root of an IO step (#1065) Inside CPU-parallel work, it runs on the CPU. F32.show's last digit may differ per lane on a decimal tie (#1079) C rounds to even, JS away from zero; both read back to the same F32. A compound type argument takes parens (#1110) Write `Maybe<(U32 & U32)>`. The parser does not backtrack, so a glued `<` reads its first argument at comparison level. A function with a `+` parameter is not a plain function (#1111) `@+x:A -> B` and `A -> B` are different types. Pass `x => f(x)` instead. The installer edits no shell file (#995) It prints the PATH line; add it to your shell's config. The hub client trusts the manifest path grammar on POSIX only (#788) The path guard is POSIX. Windows is not a supported host (see CAPACITY). A base-file helper may call a law filled below it (#793) `base.bend` carries this carve-out and the Lean formalization states it. User files do not get it. A handle type is a law of Base (#825) `File`, `Socket`, `Window` and the other handle types are laws that only Base may leave unfilled. A user law of kind `Type` counts as open, so a custom effect reuses a Base handle type. Opening this to user files touches consistency; we will address the gap later. CAPACITY (a small team keeps the language at a size it can maintain) Windows is not supported (#788) Use WSL. No Vulkan or other extra GPU lanes (#811) Metal and CUDA only. `!` runs on the CPU on WSL2 GPUs (#1066) They lack concurrent managed access; a device copy of the corpus is a second memory model we cannot maintain. No DNS, TLS, crypto or HTTP in Base (#846) TCP.connect takes an IPv4 address; JS's IO loop cannot wait on a lookup. TLS and crypto need OpenSSL: build them as hub packages over TCP bytes. No cancellation of blocking effects (#1034) IO.within bounds the wait; the losing effect still runs to its end. Server helpers stay out of Base (#1106, #1117) Base holds the effects no library can build. A confined open or a sendfile is a foreign effect: ship it as a hub package. gcc is not supported (#773) See DESIGN. OPEN (no solution we trust yet; patches would cost us control of the codebase) F32 NaN payload bits are not preserved on the JS lane (#797, #872) An F32 is a JS number there. A bit-exact representation measured 7-8x slower on F32 code (nbody 3.5 s -> 23.7 s), so the C lane is the reference and JS keeps the number. A program that reads those bits as a dependent tag takes the two lanes down two arms, and the arm JS takes may duplicate an affine value (#872). The C lane is the reference there too. RUNTIME (the theory allows it, the runtime does not run it yet; we remove these over time; do not open an issue) An unbalanced `Array` tree fail-stops at runtime (#808) `ALeaf`/`ANode` are public, so the checker admits a tree whose halves differ; every backend stores an array as one flat block and traps on such a node. A depth index would fix it in the type, but Bend does no inference, so `xs[i]` would have to become `xs[i^d]`; we chose not to. Like the Nat cap and the block-class cap below, this is a runtime limit, not a design. A Nat past 2^48-1, or an array past block class 31, fail-stops (#779) Immediates hold 48 bits; blocks have 32 classes. The theory has no such bound. A value with more than 2^24-1 live copies fail-stops on the C lane (#1267) Copies of a `+` value share it through one 24-bit count; JS keeps no count and runs on. `Array.new(T, d, x)` makes 2^d copies of x, so a computed x stops it at depth 24 there. For more copies, build x again for each group: e.g. an `Array.new` at depth 23 per build, joined by `ANode`. SOON (we will add it; do not open an issue) U64 (#1027) We will add it ourselves; we do not merge PRs for U64 or U128. F64 (#1120) It needs U64's 64-bit word design; we add both together, and we do not merge PRs for F64. F32 that computes in the checker (#1017) F32 operations are axioms today; bit-level definitions are planned. Continuation passing for non-tail calls on the JS lane (#798, #802) Deep recursion (String.length over 100k chars, List.length over 200k elements) overflows the host stack. Until then String.length is an intrinsic; other folds may overflow. A native library target for pure defs (#813) Today the C output is one program with a `main`. Exporting chosen defs with a header and a lifecycle is planned, not scheduled.