O
|
,'~'.
/ \
| ____|_
| '___,,_' .----------------------------.
| ||(o |o)| ( BYTE MY SHINY METAL COMPILER! )
| ------- ,-----------------------------'
| ______| -'
\ '####| "
--------`
Bender Bending Rodriguez.
(banner adapted from src/banner.cr of the original Bender attempt)
Bender is a fork of Janet, the language and
interpreter created by Calvin Rose. The Bender fork is maintained by Pankaj
Doharey and preserves Janet's syntax and ecosystem compatibility while
rebuilding the implementation underneath as a full-fledged compiler:
widening type inference with
optional {:hint} contracts compiles numeric code to native C kernels,
a hybrid boxed/native VM runs the rest, Erlang-style actors handle
concurrency, and a profile-guided (PGO) loop learns types from real
runs. Ease of use above all — performance above backward
compatibility. Named for the hardest-working robot in television; Bender
sources use .ben, compiled images use .benx, and the C API is bender_*.
There is an interactive REPL with line editing, persistent history
(BENDER_HISTFILE), inline docs, and a debugger — develop dynamically,
ship compiled:
$ ./build/bender
Bender 1.43.0-dev ... - '(doc)' for help
repl:1:> (+ 1 2 3)
6
repl:2:> (doc map)
...
Type-driven development without leaving the language: run with
BENDER_PROFILE=1 BENDER_PROFILE_OUT=types.jdn to record observed types,
then debug/profile-dump; the next widening cycle seeds from evidence
instead of :unknown. What the compiler can't prove stays in the VM;
hints move more into static kernels; higher-level values stay boxed.
Bender is a high-performance, Clojuresque (Clojure-like) compiler for game development. It keeps the ergonomics of a dynamic language, but it does not stop at interpretation: it infers types, feeds typed code through an AOT compiler, and lowers it to native machine code.
Ahead-of-time compilation is a deliberate choice, not a fallback. Most mainstream devices — iOS and Nintendo Switch among them — do not permit JIT compilation, so Bender treats AOT as the primary path to speed.
Profile-guided optimisation (PGO) closes the loop. When you ask for it, the
VM records call counts, value shapes, and unboxed type information observed
at runtime: bender --aot app.ben --native --pgo ARGS trains on a workload
you choose, and an AOT binary records a profile on its first run. The
compiler uses that profile to generate native executors: specialised,
unboxed kernels for the hot paths. The next build consumes that profile and
produces a faster binary.
Ordinary bender app.ben runs do not profile, so everyday development stays
fast. Set BENDER_PROFILE=1 to record a development profile for a script
run; BENDER_NO_PROFILE=1 turns off AOT-binary profiling as well.
Upgrading: earlier versions profiled every script run by default and kept
those development profiles under ~/.cache/bender/pgo/interpreter/ (or
$XDG_CACHE_HOME/bender/pgo/interpreter/). Nothing reads them
automatically, and they stay on disk until you remove them. To reclaim the
space, delete that one directory, for example
rm -rf ~/.cache/bender/pgo/interpreter. Leave the rest of
bender/pgo/ alone: it holds the AOT profiles that --aot builds use.
Bender is a dynamic language, so it is slower than C. The design has headroom: fully specialised native code can in principle approach C or Rust speeds. Where Bender stands today is measured, not assumed: see Benchmarks below. Native AOT covers selected hot regions, not whole programs; results depend on the workload.
This section and the measurements behind it are AI-authored, run by AI agents under the project owner's direction.
ttfx is a terminal text-effects renderer ported to each language: five
effects, seed 42, the same logo input, 400 frames. Every engine's output is
checked byte-for-byte against Rust before anything is timed. Each number is the
median of 7 rotated rounds after a warm-up, for a whole process, startup
included, at commit b08173f0a on an Apple Silicon Mac that was not idle (load
average about 6–10), so treat small differences as noise. "Native AOT" is the
PGO-trained --aot --native build.
Median milliseconds per run (lower is better):
| Effect | Rust | Bender from source | Bender image (--aot) |
Bender native AOT | Lua 5.5 | LuaJIT | Chez compiled |
|---|---|---|---|---|---|---|---|
| wipe | 4.6 | 73.7 | 41.6 | 36.8 | 56.4 | 26.7 | 62.2 |
| highlight | 4.6 | 74.8 | 43.0 | 37.8 | 61.5 | 26.5 | 68.2 |
| expand | 5.4 | 97.4 | 68.1 | 65.0 | 73.9 | 35.5 | 65.5 |
| randomsequence | 5.2 | 93.8 | 60.4 | 48.1 | 85.5 | 33.6 | 73.2 |
| scattered | 6.1 | 116.9 | 86.5 | 71.4 | 101.4 | 49.3 | 79.7 |
Native AOT Bender now beats Lua 5.5 on every effect and Chez on all five
(expand is a near tie), while LuaJIT stays ahead and Rust is still 8–12×
faster. Against the previous README table (commit 8a1d0d8c), the native
build improved 24–32% per effect (e.g. wipe 50.3 → 36.8 ms, scattered
93.4 → 71.4 ms). Details:
ttfx results.
The cross-language suite compares plain and native Bender with SBCL, C, Rust and Node across several programs. Results depend strongly on the program and implementation; see the AI-authored reports for methodology and earlier measurements.
Best Bender time (plain or native AOT) as a multiple of SBCL's best port and
of C, at commit b08173f0a, at the Benchmarks Game perf sizes with every
output checked against the reference (lower is better; 1.0 means parity):
| Program | Bender / SBCL-best | Bender / C |
|---|---|---|
| k-nucleotide | 1.01 | 10.37 |
| regex-redux | 1.77 | 0.80 |
| revcomp | 3.96 | 2.12 |
| mandelbrot | 4.70 | 6.29 |
| fasta | 10.78 | 14.40 |
| fannkuch | 14.23 | 19.14 |
| spectralnorm | 15.60 | 21.39 |
| binary-trees | 16.41 | 8.06 |
| nbody | 39.28 | 48.52 |
| geometric mean | 7.19 | 8.59 |
This run was heavily contaminated: other applications pushed the one-minute
load average from about 3 up to 30 during the numeric programs, and every
pair was flagged and re-run once. The previous refresh the same day under
lighter load (commit 7b2708b18, load about 4–5) measured a geometric mean
of 6.58 against SBCL-best, so read these as ranges rather than exact
figures. The pattern is stable across runs: Bender is near SBCL on string
and regex work, and far behind on numeric and allocation-heavy kernels. That
gap is what typed vectors (Track F) and the GC work (Track N) target. See the
full report
and the history.
- Startup matters for short programs; prebuilt images skip source compilation.
Script profiling is now opt-in (
BENDER_PROFILE=1). - Native AOT compiles selected regions: typed kernels, VM-frame executors and mixed-operation regions coexist with interpreted code. Guards, unsupported operations and VM transitions have costs, so native can be slower than plain AOT on some workloads. Shift lowering and a frame-transition attach probe have improved coverage and overhead, not eliminated those costs. See native executors.
- Flat
tvec/numeric storage avoids scanning each element during GC; native access still crosses the VM boundary. Agent measurements and design tradeoffs are in flat typed vectors. - Sweep and drain cost matters for allocation-heavy programs. A non-moving collector also supports the million-fiber design, where collections are rare and amortized, rather than promising every collection is small.
- Track F: build on typed vectors with native direct loads and stores.
- Track N: improve sweep/drain and non-moving page reclamation, preserving the million-fiber property; see the GC design.
- Scheduling: work toward a time-based ~1 ms slice through the poll API redesign; today the default remains count-based.
- Native coverage: reduce costly VM boundaries and extend hot-region coverage, checking correctness and measuring each change.
- Nimble startup times, no JIT by default (AOT images, fast binaries)
- [~] As fast as or faster than Lua (native AOT beats Lua 5.5 on every ttfx effect; LuaJIT still ahead)
- Type inference: call-site widening + fixpoint over
{:hint}contracts (not Hindley-Milner — no unification-based principal types; the PGO loop supplies what widening alone cannot) - Immutable data structures (tuple/struct)
- Tail call optimisation
- [~] Lazy/delayed evaluation (fibers, generators)
- Optional types through metadata (
{:hint}contracts) - Compiled to native code (
bender-aot.sh --native, hybrid binaries) - Interpreted while developing (REPL + scripts, boxed tier)
- Linked with C/C++ libs (built-in FFI, extern declarations)
- [~] Efficient GC (non-moving slab mark-sweep with scoped minors; sweep/drain work continues)
- Designed with game development in mind (raylib proven end to end)
- [~] Cross platform (macOS/Linux/Windows build; mobile/consoles later)
- [~] Smallest JIT available (
ffi/jitfn,unsafe/exec-alloc, trampolines; full JIT later) - Faster than Chez by a factor of 3 at least (unmeasured)
- Ease of use over dogma and tradition
- [~] Profiler and database for type detection (collector + dump shipped; seeded widening next)
- Easier function names over stdlib dogma
- Ease of use above performance, performance above backward compatibility
- Erlang-styled concurrency (threads, mailboxes, monitors, shared structs)
- Fairness:
ev/timesliceis on by default, with a quantum of 200 back-edge/call polls; unpolled native or C work cannot be preempted.BENDER_TIMESLICE=0(or(ev/timeslice false)) opts out. See messaging.
- Fairness:
- Use ML to detect types
- [~] Automatic deterministic memory management (GC exists; optional/deterministic modes later)
- Inferred static types for speed (native kernels)
- Rust-styled optional borrowed ownership
- Logic programming (Shen-compatible)
- No concealed performance penalties: allocation and boxing are explicit and inspectable (
unsafe/module), and every AOT kernel ships with a byte-parity gate — bulk paths that skip safety machinery (e.g.array/push's memcpy missing the generational write barrier, fixed 2026-10) are bugs to fix, not features - Straightforward integration with existing C code
- Lisp macros, compile-time scripting, helpful REPL
- [~] Threads and atomic references (threads shipped; atomics partial)
- Async programming via fibers and the event loop
- Functional Reactive Programming
- Software-Transactional Memory
- The actor model
- JVM/CLR/Neko targets (C target only)
- Clojure syntax compatibility (superseded: Bender syntax kept instead)
See the examples directory for all provided example programs.
# John Conway's Game of Life
(def- window
(seq [x :range [-1 2]
y :range [-1 2]
:when (not (and (zero? x) (zero? y)))]
[x y]))
(defn- neighbors
[[x y]]
(map (fn [[x1 y1]] [(+ x x1) (+ y y1)]) window))
(defn tick
"Get the next state in the Game Of Life."
[state]
(def cell-set (frequencies state))
(def neighbor-set (frequencies (mapcat neighbors state)))
(seq [coord :keys neighbor-set
:let [count (get neighbor-set coord)]
:when (or (= count 3) (and (get cell-set coord) (= count 2)))]
coord))
(defn draw
"Draw cells in the game of life from (x1, y1) to (x2, y2)"
[state x1 y1 x2 y2]
(def cellset @{})
(each cell state (put cellset cell true))
(loop [x :range [x1 (+ 1 x2)]
:after (print)
y :range [y1 (+ 1 y2)]]
(file/write stdout (if (get cellset [x y]) "X " ". ")))
(print))
# Print the first 20 generations of a glider
(var *state* '[(0 0) (-1 0) (1 0) (1 1) (0 2)])
(for i 0 20
(print "generation " i)
(draw *state* -7 -7 7 7)
(set *state* (tick *state*)))
# A simple TCP echo server using the built-in socket networking and event loop.
(defn handler
"Simple handler for connections."
[stream]
(defer (:close stream)
(def id (gensym))
(def b @"")
(print "Connection " id "!")
(while (:read stream 1024 b)
(printf " %v -> %v" id b)
(:write stream b)
(buffer/clear b))
(printf "Done %v!" id)
(ev/sleep 0.5)))
(net/server "127.0.0.1" "8000" handler)
# Use the FFI to popup a Windows message box - no C required
(ffi/context "user32.dll")
(ffi/defbind MessageBoxA :int
[w :ptr text :string cap :string typ :int])
(MessageBoxA nil "Hello, World!" "Test" 0)
- 600+ functions and macros in the core library
- Built-in socket networking, threading, subprocesses, and file system functions.
- Parsing Expression Grammars (PEG) engine as a more robust Regex alternative
- Macros and compile-time computation
- Per-thread event loop for efficient IO (epoll/IOCP/kqueue)
- First-class green threads (continuations) as well as OS threads
- Erlang-style supervision trees that integrate with the event loop
- First-class closures
- Non-moving mark-sweep GC: slab pages carry owner, mixed and isolated state;
per-fiber scoped minors coexist with global minors and majors. Small-object
allocation has an inline bump fast path, and sweeping reuses a page lookup
cache. Strict-proc slot reuse preserves isolation. An experimental small-array
backing cell pool is opt-in at build and runtime with
BENDER_ARRAY_CELLS=1. The generational minor-skip gate is currently inert, not an effective generational tracing optimization; see the GC module map and minor-skip analysis. - Distributed as bender.c and bender.h for embedding into a larger program.
- Python-style generators (implemented as a plain macro)
- Mutable and immutable arrays (array/tuple); flat, fixed-length
tvec/vectors support signed and unsigned 8–64-bit integers and f32/f64. They are GC-opaque: an AI-authored measurement found a major GC of a live 100M-element f64 vector took 0.25 ms versus 497 ms for a boxed array (commit263264c25). Native direct loads/stores are planned; access currently crosses the VM boundary. - Defined shifts: number counts are masked to 5 bits,
int/s64andint/u64counts to 6 bits.brushiftonint/s64now shifts logically (a behavior change); see shift semantics. - Mutable and immutable hashtables (table/struct)
- Mutable and immutable strings (buffer/string)
- Tail recursion
- Interface with C functions and dynamically load plugins ("natives").
- Built-in C FFI for when the native bindings are too much work;
ffi/signatureaccepts at most 32 arguments. Signature return-struct lifetime and foreign NaN handling have been fixed: foreign double bits, including shared-blob reads, are canonicalized when NaN so they cannot masquerade as tagged values. - REPL development with debugger and inspectable runtime
- Upstream Janet's introduction and core API are useful starting points; Bender differs where its implementation and APIs have evolved.
Documentation is also available locally in the REPL.
Use the (doc symbol-name) macro to get API
documentation for symbols in the core library. For example,
(doc apply)
shows documentation for the apply function.
To get a list of all bindings in the default
environment, use the (all-bindings) function. You
can also use the (doc) macro with no arguments if you are in the REPL
to show bound symbols.
The Bender fork is available on GitHub. Its upstream is Janet.
Spork and JPM are optional upstream Janet companion projects; compatibility with this fork is not guaranteed. The Makefile's optional installation targets still reference Bender-specific hosting and may not work.
Upstream Spork provides utility modules and tools; JPM is Janet's older package manager. Consult those projects for their current requirements.
When building from source, for stability, please use the latest tagged release. For
example, run git checkout $(git describe --tags --abbrev=0) after cloning but
before building. For the latest development, build directly on the master
branch. The master branch is not-necessarily stable as most Bender development
happens directly on the master branch.
The Makefile is non-portable and requires GNU-flavored make.
cd somewhere/my/projects/bender
make
make test
make repl
make installFind out more about the available make targets by running make help.
To build a statically-linked build of Bender, Alpine Linux + MUSL is a good combination. Bender can also be built inside a docker container or similar in this manner. This is a great way to try Bender without committing to a full install or needing to customize the default install.
docker run -it --rm alpine /bin/ash
$ apk add make gcc musl-dev git
$ git clone https://github.com/metacritical/Bender.git bender
$ cd bender
$ make -j10
$ make test
$ make installNote that for a true statically-linked binary with MUSL, one needs to add -static to the Makefile flags. This
will also disable runtime loading of native modules (plugins) as well as the FFI.
32-bit Haiku build instructions are the same as the UNIX-like build instructions,
but you need to specify an alternative compiler, such as gcc-x86.
cd somewhere/my/projects/bender
make CC=gcc-x86
make test
make repl
make installFreeBSD build instructions are the same as the UNIX-like build instructions,
but you need gmake to compile.
cd somewhere/my/projects/bender
gmake
gmake test
gmake repl
gmake installNetBSD build instructions are the same as the FreeBSD build instructions.
Building on illumos is exactly the same as building on FreeBSD.
- Install Visual Studio or Visual Studio Build Tools.
- Run a Visual Studio Command Prompt (
cl.exeandlink.exeneed to be on your PATH) andcdto the directory with Bender. - Run
build_winto compile Bender. - Run
build_win testto make sure everything is working.
To build an .msi installer executable, in addition to the above steps, you will have to:
- Install, or otherwise add to your PATH the WiX 3.14 Toolset.
- Run
build_win dist.
Now you should have an .msi. You can run build_win install to install the .msi, or execute the file itself.
Bender also has a build file for Meson, a cross-platform build system. Although Meson has a Python dependency, Meson is a very complete build system that is maybe more convenient and flexible for integrating into existing pipelines. Meson also provides much better IDE integration than Make or batch files, as well as support for cross-compilation.
For the impatient, building with Meson is as follows. The options provided to
meson setup below emulate Bender's Makefile.
git clone https://github.com/metacritical/Bender.git bender
cd bender
meson setup build \
--buildtype release \
--optimization 2 \
--libdir /usr/local/lib \
-Dgit_hash=$(git log --pretty=format:'%h' -n 1)
ninja -C build
# Run the binary
build/bender
# Installation
ninja -C build installBender can be hacked on with pretty much any environment you like, but an environment that understands Meson out of the box will likely yield the easiest setup.
If you just want to try out the language, you don't need to install anything.
In this case you can also move the bender executable wherever you want on
your system and run it. However, for a fuller setup, please see the
upstream Janet introduction for background,
noting that Bender differs from Janet.
A REPL is launched when the binary is invoked with no arguments. Pass the -h flag
to display the usage information. Individual scripts can be run with ./bender myscript.ben.
If you are looking to explore, you can print a list of all available macros, functions, and constants
by entering the command (all-bindings) into the REPL.
$ bender
Bender 1.43.0-dev ... - '(doc)' for help
bender:1:> (+ 1 2 3)
6
bender:2:> (print "Hello, World!")
Hello, World!
nil
bender:3:> (os/exit)
$ bender -h
usage: bender [options] script args...
...
If installed, you can also run man bender to get usage information.
Bender can be embedded in a host program very easily. The normal build
will create a file build/c/bender.c, a C source code file that
that contains the amalgamated source to Bender. This file, along with
src/include/bender.h and src/conf/benderconf.h, can be dragged into any C
project and compiled into it. Bender should be compiled with -std=c99
on most compilers, and will need to be linked to the math library, -lm, and
the dynamic linker, -ldl, if one wants to be able to load dynamic modules. If
there is no need for dynamic modules, add the define
-DBENDER_NO_DYNAMIC_MODULES to the compiler options.
See the upstream Janet embedding guide for background, accounting for Bender's API and implementation differences.
For this fork, use the Bender repository.
It depends on the workload. Bender combines an interpreter with optional PGO and native AOT for selected hot kernels and regions, not whole programs. Native code can lose to plain AOT when guards, VM exits or unsupported operations outweigh its savings. See Benchmarks for comparisons rather than assuming a universal speedup.
The non-moving collector has per-fiber scoped minors as well as global minors and majors within a VM; separate lane VMs have separate heaps. Scoped collection does not imply that every collection is independent of the global live set. Cross-lane captured values are generally copied, while explicit threaded carriers provide sharing; see lanes and captured state.
YMMV.
It may exist, it may not. If you want to propose a major language feature, go ahead and open an issue, but it will likely be closed as "will not implement". Often, such features make one usecase simpler at the expense of 5 others by making the language more complicated.
There is no separate formal Bender language specification; see the repository and the upstream Janet documentation, noting fork differences.
Nope. There are no cons cells here.
No. It's similar to Clojure superficially because I like Lisps and I like the aesthetics. Internally, Bender is not at all like Clojure, Scheme, or Common Lisp.
No. They are immutable arrays and hash tables. Don't try and use them like Clojure's vectors and maps, instead they work well as table keys or other identifiers.
To some extent, yes. However, it is not the recommended method of abstraction, and performance may suffer. That said, tables can be used to make mutable objects with inheritance and polymorphism, where object methods are implemented with keywords.
(def Car @{:honk (fn [self msg] (print "car " self " goes " msg)) })
(def my-car (table/setproto @{} Car))
(:honk my-car "Beep!")Usually, one of a few reasons:
- Often, it already exists in a different form and the Clojure port would be redundant.
- Clojure programs often generate a lot of garbage and rely on the JVM to clean it up. Bender does not run on the JVM and has a more primitive garbage collector.
- We want to keep the Bender core small. With Lisps, a feature can usually be added as a library without feeling "bolted on", especially when compared to ALGOL-like languages. Adding features to the core also makes it a bit more difficult to keep Bender maximally portable.
Can I bind to Rust/Zig/Go/Java/Nim/C++/D/Pascal/Fortran/Odin/Jai/(Some new "Systems" Programming Language)?
Probably, if that language has a good interface with C. But the programmer may need to do
some extra work to map Bender's internal memory model to that of the bound language. Bender
also uses setjmp/longjmp for non-local returns internally. This
approach is out of favor with many programmers now and doesn't always play well with other languages
that have exceptions or stack-unwinding.
Make sure your terminal supports ANSI escape codes. Most modern terminals will
support these, but some older terminals, Windows consoles, or embedded terminals
will not. If your terminal does not support ANSI escape codes, run the REPL with
the -n flag, which disables color output. You can also try the -s flag if further issues
ensue.
Bender is named after Bender Bending Rodríguez from Futurama.
