Skip to content

Web Playground - #859

Closed
kungfooman wants to merge 23 commits into
bendlang:mainfrom
kungfooman:playground
Closed

kungfooman wants to merge 23 commits into
bendlang:mainfrom
kungfooman:playground

Conversation

@kungfooman

Copy link
Copy Markdown

Run, teach and show Bend2 entirely client-side!

Summary

Turns the web-playground sketch into a complete in-browser Bend2
environment: full compiler in a worker, interactive stdin, a canvas
display polyfill for Window apps, the repo demos loadable as static
files, a 20-step curriculum, an ACE editor with Bend highlighting, deep
links, and a static exporter — plus the compiler robustness fixes the
playground's small stacks forced (iterative walkers, verified
byte-identical).

Serve it with bun bend2/main.ts playground, or bun bend2/play/export.ts ./play-dist and any static host (works at domain
root or subpath, no backend after build).

🎮 TRY IT — click, compile, play

Live at https://bend.runtimetypeinspector.org/ — pick one, hit
Compile to JS and run, play in the Display tab. No install.

🏓 Pong — ?demo=app_pong_game_2d

Two paddles, one ball, 512×512, 60 fps, compiled from Bend in your
browser. Grab a friend: left paddle W/S, right paddle ↑/↓,
Esc quits. Every frame is a Bend quadtree image; every keypress is a
Bend Event.

🪐 Ray tracer — ?demo=app_ray_tracer_3d

Ray-marched spheres over a checkered plane with hard shadows, compiled
to 200 KB of JS in ~0.5 s. Fly it: W/A/S/D move,
Q/E up/down, arrows look around, Esc quits. Watch the FPS
counter top-left.

🚩 Winning Is Impossible — ?demo=app_win_is_bug_2d

A maze game that ships a formal proof you cannot win — step on the
flag anyway. Arrows/WASD to move. If you win, file a bug: it's
mathematically impossible.

🔺 Triangle — ?demo=app_triangle_2d

The smallest graphical program: recursive triangle subdivision, click
to subdivide, Esc quits. Start here if you want to read the source.

🧮 Calculator — stdin demo

Not a repo demo but the input showcase: type two numbers, get the sum —
IO.read_line line by line. Flip Ask me next to Stdin and the
worker waits on you per line.

Playground core (bend2/play/)

  • server.ts: serves the bundle plus demos/**/*.bend as static text;
    CSP locked down (connect-src 'self' for demo fetch only).
  • worker.ts: real bend.ts + comp.ts bundled for the browser, four
    actions (interpret, compile-run, compile-js, compile-c) with 30–60 s
    guards and 1 MiB output cap.
  • platform.ts: Node fs/path shim over an in-memory FS; subpath-safe
    base.bend/effs resolution.
  • runner.ts: executes compiled JS in a fresh worker; cooperative
    yielding so hot loops can't starve input, 60 Hz present pacing.
  • client.ts / index.html / style.css: editor, Results/Compiled
    tabs, cancel, copy/download, localStorage persistence.
  • export.ts: one-command static export (5 files + demos/ + vendor).
  • main.ts: bend / bend playground [--port N] CLI entry.

Interactive stdin (IO.read_line)

  • New effect IO.read_line() -> IO(Maybe<&1, String>) (bend2/effs/read_line.{c,js},
    base.bend): one line per call, None{} on EOF. Native backends read
    fd 0; the browser parks on a virtual fd and the page asks per line.
  • UI: Stdin box (Prefill / Ask-me modes) plus a live Input row with
    Send/EOF. Type-ahead works; cancel/EOF/timeout all terminate cleanly.

Display polyfill (Window in the browser)

  • window_{open,frame,close,set_title}.js grow browser branches
    (native C/node paths untouched): virtual handles, quadtree rasterizer
    mirroring the native fill ([tl,tr,bl,br], 0x00RRGGBB), arrival-order
    event lists.
  • Page: third Display tab with pixelated canvas, document-level keys
    mapped to the native table (w→119, arrows→63232+), mouse buttons and
    clipping mirrored, focus-independent. Verified end-to-end (triangle
    opens 512×512, frames carry content, Escape quits).
  • Pong, Triangle, WinIsBug, Ray tracer, Slash boss all run in
    the tab. Audio stays native-only.

Demos, curriculum, editor, links

  • Demos load as static files into a multi-file memory FS (flat
    namespace, one demo at a time), with a runnable / needs-native split
    in the picker and removable aux-file chips.
  • 20-step curriculum (01 Literals … 20 Dual numbers), each
    checker-verified, in the Start-with menu.
  • ACE editor with a custom Bend2 mode (keywords, +x/-A/~f/&2,
    types, constructors, numerals, strings, comments), vendored
    (play/vendor/, same-origin so CSP holds); Tab/colon indent, gutter,
    Ctrl/⌘+Enter to run.
  • ?demo=app_ray_tracer_3d deep links (address bar follows the picker),
    ?debug=true or the status-bar toggle for a pipeline log (key
    captures, worker messages, frame/input traffic).

Compiler robustness (forced by browser stacks)

Browser workers (~512 KB–1 MB) vs native 8 MB: deep terms blew the
stack where native never noticed. All fixes are semantics-preserving
restatements, verified by differential testing:

  • bend2/comp.ts: term_any, type_adts iterative; queue.push(...arr)
    → loops; new js_ctr_tree iterative post-order emission.
  • bend2/bend.ts: term_higher / term_lower process Ctr with an
    explicit machine; patt_term flattens PCtr chains.
  • demos/app_ray_tracer_3d/main.bend: 1000n → Nat.mul(10n, 100n)
    (same value; the checker walks syntax, so ~900 nesting levels vanish).

Verification

  • Raytracer compiles in a 256 KB worker (was RangeError at 1 MB),
    byte-identical output; par_sort and all 12 runnable demos build.
  • tests/eval, tests/io, tests/proof match pristine exactly
    (35/4, 75/25, 42/33 — failures pre-exist on both sides: network,
    display, and negative-test artifacts of a local runner).
  • Key/mouse/event pipeline proven with scripted harnesses driving the
    real runner.ts message protocol (arrival order, key-up fidelity,
    EOF, prefill/type-ahead mixes).

Known limits

  • No GPU in the browser (! runs sequentially in the JS lane); audio
    and sockets remain native-only with graceful errors.
  • bend2/bend.ts is supposed to be human-written-only: the iterative
    machines there are the one debatable hunk — take them, reshape them,
    or say the word and they move behind a flag. Everything else stays
    out of the core.

nicolas-abril and others added 17 commits September 18, 2026 12:59
New IO.read_line effect (Some{line} per call, None{} on EOF) with C,
JS and browser backends; the playground gains a Stdin box with
Prefill/Ask-me modes plus a live Input row the worker parks on.
play/export.ts writes the five static files for any dumb host, and
the browser platform canon fixes subpath hosting.
The full progression (literals to dual numbers) ships as runnable
Start-with options, generated byte-identical from checker-verified
sources.
Window effs branch to browser canvas; runner rasterizes quadtree,
paces at 60Hz and drains input per frame; client adds Display tab,
document-level keys and ?debug=true propagated to workers.
- Display programs no longer auto-kill at 30s; Stop button shows
  'Running - press Stop to quit' until you stop them.
- Parallel Sort etc. RangeError now suggests Compile to JS and run.
term_any and type_adts made iterative; queue pushes no longer spread
large arrays. Verified with --stack-size=128: pure_par_sort and all
other demos now compile in the playground worker.
Ray tracer is ~10k lines / 200KB JS and can need >30s to check in
the browser. Bump to 60s with a hint.
term_higher/term_lower recursed per Ctr level; unary numerals like
1000n elaborate to 1000-deep Succ spines. Process Ctr with an explicit
machine; flatten PCtr chains in patt_term. Raytracer 1000n becomes
Nat.mul(10n, 100n) (same value, shallow syntax). Verified at
--stack-size=128/256, zero test regressions vs pristine.
js_expr Ctr case recursed per level via .map; elaborated deep
nesting (raytracer) blew browser stacks. Same explicit machine
as term_higher/lower. Verified 128KB, suites match pristine.
Debug flag no longer URL-only: status-bar toggle, synced to ?debug.
?demo=<dir> deep-links a demo and the address bar follows the picker.
Takes formatter LSP, IO.args, new effs and guides. Conflict
resolutions keep playground CLI, iterative compiler fixes and the
wider allow-list on both sides.
Vendor ace.js + chrome theme + custom bend mode (keywords,
quantities, types, constructors). Replaces the textarea: gutter,
soft tabs and colon indent come from ACE; Ctrl+Enter runs.
Game input ignores the editor surface.
Quadtree rect-fill visits each node once instead of walking per
pixel (Pong 512p: 9.6ms -> 1.5ms, pixel-identical; 33 -> 55fps
end to end). putImageData through a desynchronized context.
Raytracer gets 1024/512/256 presets (depth + window size rewritten
on fetch, marked as adapted). 256 preview frames in 0.4s vs 13.6s
full. Generic per-demo res config; hidden for snippets.
winPixels takes native + target sizes (fast fill when equal,
sampled walk otherwise); worker scales mouse back to native
space. Display bar with free number inputs, ?w=&h= deep links,
persisted. Raytracer res presets stay for simulation depth.
Replaces per-demo res presets and free W/H inputs: fractional scales
of native size for every program, applied instantly by restarting the
demo from the same build (no recompile). ?res= deep link, caption
shows native and effective size, input maps back to native space.
W/H number inputs are the source of truth (empty follows native,
initialized from win-open); Preview/Fast/Full only fill them in.
Any apply restarts the running demo from the same build. ?w=&h=
deep links replace ?res=. Raytracer source presets deleted.
@VictorTaelin

Copy link
Copy Markdown
Contributor

This is very, very cool, thank you. But it does add a lot of code to the repo, which we don't have the capacity as a team to maintain and own just yet. Why not publish it as a separate repo? We could then mention it from our docs and in our public posts perhaps?

W/H inputs are the source of truth (initialized from win-open);
presets only fill them. Applies show unmistakable status. Raytracer
Sim full/fast/preview rewrites scene depth + recompiles.
Replaces Sim presets: any demo with a sim() config takes free
sim dimensions (depth derived as cover size); Enter reloads and
runs. Raytracer 10x20 and friends now one URL away.
Sim W/H initialize from the demo source (UI is source of truth);
quick 100/256/512 buttons; header comment only when adapted.
Raytracer HUD disables below 512px (was 40% of a 100px frame).
100x100 first frame in 0.1s.
Typing W/H resizes mid-run with no restart; canvas follows incoming
frame dims instead of dropping mismatches. Removed stale-build
restart path.
Rolling 30-frame present rate, 4Hz refresh, reset on open/finish.
Client posts display size before the program: previous javascript-
first ordering lost the race, so overrides never took (verified:
js-first opens 512, display-first opens 10x10).

New Window.size effect (C/JS/base + runner hook); runner intercepts
win-open so program, canvas and queries agree. Demos derive gameplay
and scene detail from queried size (pong/triangle/raytracer, proven
pixel-identical at defaults); page drops the raster-override and
sim-rewrite detours. Single W/H inputs, presets, ?w=?h= links.
@VictorTaelin

Copy link
Copy Markdown
Contributor

Thank you for building this; a web playground is something people ask for, and it is good to see one working.

It cannot live in the compiler repo: it brings its own bundles, its own dependencies and its own release cycle, and everything here is under one test gate and one complexity budget. Please publish it as its own repository and host it; we would be glad to link it from our README or guide so people find it. Closing the PR, with real thanks.

Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants