Native regions: a borrow-checked sublanguage inside Clojure

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

November 28, 2026 Native regions: a borrow-checked sublanguage inside Clojure One aspect of Clojure that I’ve always liked is that it is, first and foremost, a pragmatic language. It will steer you towards using functional style by default, but it also offers imperative escape hatches for performance. For example, transients are used for cases when you need to build up a big vector in a tight loop. We can mutate a transient freely, then hand back an immutable value at the end by calling persistent!. What makes transients safe is that the mutation is explicitly scoped since any further attempt to mutate the data after persistent! was called throws. So, we can have the performance benefit of working with mutable data in a local scope, and the semantics of transients ensure that it can’t leak to the outer context.

2026年11月28日 原生区域:Clojure 内部的一种借用检查子语言。我一直喜欢 Clojure 的一个方面是,它首先是一门务实的语言。它默认引导你使用函数式风格,但也为性能提供了命令式的逃生舱。例如,当你需要在紧凑循环中构建大型向量时,可以使用瞬态(transients)。我们可以自由地修改瞬态,最后通过调用 persistent! 返回一个不可变值。瞬态之所以安全,是因为其修改过程是显式限定作用域的,因为在调用 persistent! 后任何进一步修改数据的尝试都会抛出异常。因此,我们既能获得在局部作用域内处理可变数据的性能优势,又能通过瞬态的语义确保它不会泄漏到外部上下文。

I decided to see if I could apply a similar pattern at an even lower level in Jolt, which resulted in the idea of having native regions. A region drops out of the managed runtime entirely to run as plain C, then returns a Jolt array at the end:(require ‘[jolt.native :refer [native]]) (defn norm [^doubles xs] (native [^doubles xs] (loop [i 0 s 0.0] (if (< i (alength xs)) (recur (inc i) (+ s (* (aget xs i) (aget xs i)))) (Math/sqrt s))))) The body of a native macro is a numeric subset of Clojure that can be safely compiled to C. When jolt build produces a binary, the region’s C is compiled and linked in, while in the REPL or under jolt run, the code gets compiled by a JIT the first time the call site loads.

我决定看看是否能在 Jolt 中以更低的层面应用类似的模式,这产生了原生区域(native regions)的想法。一个区域会完全脱离托管运行时,以纯 C 语言运行,最后返回一个 Jolt 数组:(代码略)。native 宏的主体是 Clojure 的一个数值子集,可以安全地编译为 C。当 jolt build 生成二进制文件时,区域的 C 代码会被编译并链接进去;而在 REPL 或 jolt run 下,代码会在调用点首次加载时通过 JIT 进行编译。

Why not just call C? You might ask why even bother with such a mechanism since Jolt already supports FFI. Naturally, before diving into writing any code, I did a bit of testing with heavy numerical computation linked as a static native library. As expected, the C ran 6.3x faster than hinted Jolt, but the cost of getting data across the boundary overshadowed the benefits for small amounts of data. Opening an FFI arena, allocating into it, then copying doubles back out using write-array takes hundreds of ns. So, FFI is only useful when there is a significant amount of work being done to justify the overhead.

为什么不直接调用 C?你可能会问,既然 Jolt 已经支持 FFI,为什么还要费心搞这种机制。自然地,在深入编写代码之前,我针对作为静态原生库链接的繁重数值计算进行了一些测试。正如预期的那样,C 的运行速度比带有提示的 Jolt 快 6.3 倍,但对于少量数据而言,跨边界传输数据的成本抵消了这些收益。打开 FFI 区域、在其中分配内存,然后使用 write-array 将双精度浮点数复制出来需要数百纳秒。因此,只有在有大量工作需要完成以抵消开销时,FFI 才有用。

On the other hand, regions don’t need to marshal anything because Jolt’s double-array is a Chez Scheme flvector, and emitted C can be written directly against its layout. When a region borrows a ^doubles or a ^longs argument, C gets a pointer to the array’s own storage where it can read and write the elements in place. And that’s how regions skip having to copy the data along with all the ceremony involved in the FFI layer. Since the region works directly on memory Jolt already owns, the overhead for each call is just a few nanoseconds.

另一方面,区域不需要进行任何编组(marshal),因为 Jolt 的 double-array 是一个 Chez Scheme flvector,生成的 C 代码可以直接针对其布局编写。当一个区域借用一个 ^doubles 或 ^longs 参数时,C 会获得指向数组自身存储空间的指针,从而可以直接读取和写入元素。这就是区域跳过数据复制以及 FFI 层涉及的所有繁琐步骤的方式。由于区域直接在 Jolt 已经拥有的内存上工作,每次调用的开销仅为几纳秒。

Memory safety without a garbage collector. One tricky aspect of regions is that they bypass the GC. Since arrays get created using calloc, they have to be freed exactly once on every path, including cases when something throws inside a loop. Here, Jolt borrows ideas from Carp to track ownership with a pass modelled on Carp’s Memory.hs approach. Every array a region allocates must have a single owner, and its ownership has to move when it’s passed from one owner to another. Reading an array constitutes a borrow, allowing the checker to confirm that it’s still live at the point of use. When a let scope ends, it frees the values that haven’t been given away, while an error exit will free whatever is left live at the point of failure. The only way an array can leave a region is as a fresh Jolt array.

没有垃圾回收器的内存安全。区域的一个棘手之处在于它们绕过了 GC。由于数组是使用 calloc 创建的,它们必须在每条路径上被精确释放一次,包括循环内抛出异常的情况。在这里,Jolt 借鉴了 Carp 的思想,通过模拟 Carp 的 Memory.hs 方法的传递来跟踪所有权。区域分配的每个数组都必须有一个单一的所有者,当它从一个所有者传递给另一个所有者时,其所有权必须转移。读取数组构成借用,允许检查器确认它在使用点仍然有效。当 let 作用域结束时,它会释放尚未移交的值,而错误退出则会释放故障点处仍然存活的任何内容。数组离开区域的唯一方式是作为全新的 Jolt 数组。

A region can also call helper functions, which are defined using defnative. They are handy for things like a dot product or a vector normalization that several regions share. Helpers compile to a plain C functions inside a region while acting as ordinary Clojure functions outside them. Helpers don’t need ownership annotations because the compiler reads their body to decide what happens to an array when a region passes it to a helper. If some path in the body gives the array away by returning it or recurring with it, then the helper takes ownership of it. Otherwise the helper only borrows the array and the original caller still owns it. If you try to use an array after a helper has taken ownership of it, the compiler gives a descriptive error indicating which helper took it and why.

区域还可以调用使用 defnative 定义的辅助函数。它们对于多个区域共享的点积或向量归一化等操作非常方便。辅助函数在区域内编译为普通的 C 函数,而在区域外则表现为普通的 Clojure 函数。辅助函数不需要所有权注解,因为编译器会读取它们的主体,以决定当区域将数组传递给辅助函数时会发生什么。如果主体中的某条路径通过返回或递归移交了数组,那么辅助函数就会获得它的所有权。否则,辅助函数仅借用该数组,原始调用者仍然拥有它。如果你试图在辅助函数获得所有权后使用数组,编译器会给出一个描述性错误,指出是哪个辅助函数获取了它以及原因。

Typed using existing hints. The only type annotations a region needs are the hints on its initial parameters: ^long, ^double, ^boolean, ^doubles, ^longs and ^bytes. Everything else can be inferred by the compiler, meaning that helpers used in a region don’t need hints of their own. Each defnative also gets compiled once per distinct set of argument types at its call sites, which is inspired by the way Carp concretizes its generic functions.

使用现有提示进行类型化。区域唯一需要的类型注解是其初始参数上的提示:^long、^double、^boolean、^doubles、^longs 和 ^bytes。其他所有内容都可以由编译器推断,这意味着在区域中使用的辅助函数不需要自己的提示。每个 defnative 也会在其调用点针对每组不同的参数类型编译一次,这受到了 Carp 具体化其泛型函数方式的启发。

Threads and the collector trade offs. Since Chez uses a stop-the-world collector which waits for every active thread to reach a safe point, a plain foreign call has to keep its thread active resulting in a long-running region stalling garbage collection for the whole process. This is the famous Python GIL problem we’re all familiar with. Jolt follows G1’s region pinning and GHC’s safe foreign calls instead. Each array is first pinned within the region that borrows it so the collector won’t move it, then the call goes through Chez’s __collect_safe convention when the thread steps out of the runtime. This way, other threads can keep running and collecting while the pinned arrays stay put. To ensure that nothing can unwind in the interim, interrupts are disabled between locking and unlocking, nor is region code allowed to throw an exception into Scheme or call back into it.

线程和垃圾回收器的权衡。由于 Chez 使用的是“停止世界”(stop-the-world)回收器,它会等待每个活动线程到达安全点,因此普通的外部调用必须保持其线程处于活动状态,这会导致长时间运行的区域阻塞整个进程的垃圾回收。这就是我们都熟悉的著名的 Python GIL 问题。Jolt 转而遵循 G1 的区域固定(region pinning)和 GHC 的安全外部调用。每个数组首先在借用它的区域内被固定,这样回收器就不会移动它,然后当线程退出运行时,调用会通过 Chez 的 __collect_safe 约定。这样,其他线程可以继续运行和回收,而固定的数组则保持原位。为了确保在此期间没有任何东西可以展开(unwind),锁定和解锁之间的中断被禁用,区域代码也不允许向 Scheme 抛出异常或回调它。

Since pinning regions this way costs about 45ns a call, the overhead ends up dominating for a region that finishes quickly. To address that, there is a ^:hold-gc hint to opt into a plain call instead.

由于以这种方式固定区域每次调用大约需要 45 纳秒,对于快速完成的区域,这种开销最终会占据主导地位。为了解决这个问题,有一个 ^:hold-gc 提示可以选择进行普通调用。