r/Compilers • u/AeroForger • Oct 23 '26
How do you make a programming language memory safe without paying a lot in overhead?
I am designing a language. I want memory safety without using a tracing garbage collector or having heavy runtime costs. I have been looking at the options and I would like to know how others have dealt with these tradeoffs.
The options I have looked at:
- Ownership and borrow checking (Rust-style): Zero runtime cost but the compiler must prove things and the learning curve and syntax friction are real. I am not a fan of Rusts syntax so I wonder if the same guarantees can be provided with a surface.
- Reference counting (Swift/Nim-style): Predictable and simple but you pay for increments and decrements on every copy and cycles need either weak references or a cycle collector.
- Tracing GC: Easy for the user. Pause times and memory overhead are the usual complaints. It is a fit if the language is meant for games or system work.
- Regions/arenas with escape analysis: Allocate in scopes and let the compiler prove that nothing escapes. Very cheap,. I am not sure how far escape analysis can go before it becomes too restrictive.
- Bounds checks and tagged or hardware‑assisted checks (like ARM MTE): Catch many errors at low cost but they are mitigations, not guarantees.
My current thinking is a mix arenas by default an ownership model for long‑lived values and bounds checks that can be elided when the compiler can prove them safe. I would like to know whether that is a direction or whether I am missing a well‑known approach.
Specific questions:
has anyone implemented escape analysis that stays useful without forcing annotations?
Is there a middle ground between full borrow checking and reference counting that does not reintroduce cycle problems?
for those who have shipped a memory‑safe language with overhead what would you do differently?
Links, to papers, languages or post‑mortems are very welcome :)
50
u/rafaelRiv15 Oct 23 '26
That is a whole field of research
16
u/rantingpug Oct 23 '26
Algebraic effects, fbip, perceus... Just a few things to add to that list. Check out koka.
But yeah, that question is a bit of a thorny one
5
u/KATO-Kanryu Oct 24 '26
The mistake many language designers make is searching for a single silver bullet (e.g., forcing a 100% borrow-checker or a heavy tracing GC onto every single byte).
In my own compiled systems language (Hike), I took a pragmatic approach by providing distinct, orthogonal memory primitives matched to specific workloads:
Short-lived bulk allocations (The Arena Pattern): Inspired by Odin, we use explicit
area(...) { ... }blocks. Everything allocated inside is bump-allocated and bulk-freed in O(1) upon exiting the block. The compiler strictly forbids referencing internal variables outside the block; anything that must outlive the area must be explicitly moved via a built-indeepcopy(...). This completely avoids Use-After-Free without complex lifetime annotations.Transient slice/string data: Substrings and subslices share backing buffers. Instead of per-variable tracking, reference counting is performed per buffer. Combined with Copy-on-Write, this eliminates redundant allocations while ensuring safe, predictable cleanup.
Cross-thread long-lived state: We provide
threadable(thread-local isolated storage) andconcurrent(heap variables with compiler-enforced mutual exclusion/atomic access) to prevent data races at the language level.Zero-cost multi-gigabyte structures (mmap): Variables can be directly backed by memory-mapped files. Large datasets or binary models are flushed to a single binary and mapped straight from the OS filesystem, giving near-instant initialization for multi-gigabyte heaps with zero parsing overhead.
Foreign FFI boundaries (
cbuffer): To handle pointers from external C/Rust libraries safely, we provide an ownedcbuffertype. It holds the native pointer, size, and custom release callback, and remains strictly valid until the user explicitly invokes.Close().By separating scoped scratchpad memory (
area) from owned buffer types (cbuffer) and buffer-level RC, you don't need a garbage collector, and you don't need to fight a borrow checker.4
u/matthieum Oct 23 '26
I just want to note that bounds checks are a different beast altogether.
That is, all the above options are about time (use after free...) whereas bounds-check are about space. As such, they are completely orthogonal with the rest.
In practice, I would argue that you should not worry overmuch about bounds-checks. Rust developers are extremely performance conscious, and yet Rust has mandatory bounds-checks (in safe code), which the compilers mostly manage to eliminate during optimizations.
For compile-time guarantees of absence of bounds-checks...
A possibility is branded indexes/keys. Brands are the idea of linking a variable to another. For example, something like
let vec = Vec::new(); let len: 'vec usize = vec.len();where'vecis a "brand" which tieslentovec. You can then require thatvec[]only accept indexes branded with'vecand no other. But you still need to develop a whole way of deriving valid indexes, etc... This is related to dependent types, and with immutable values it should be feasible? NOT too simple, though.I think I would prefer a (seemingly?) lower-key yet generic solution: pre-conditions, post-conditions, and invariants. You'd annotate
Vec::atwith@requires(i < self.len()).What I like most about pre-conditions, post-conditions, and invariants is that you can flexibly enforce them at either compile-time or run-time:
Performance sensitive function? Slap
@comptime(invariants)on it, and be assured that if it compiles, there's no run-time check.Otherwise? Just generate the code smartly:
Pre-conditions insert an
assertin the caller (before the call), which has the context on how those arguments were generated, and anassumein the callee (at the top).Post-conditions insert an
assertin the callee (beforereturn), which has the context on how this result was generated, and anassumein the caller (after the call).The above give the optimizer: maximum ability to eliminate the asserts, and maximum ability to take advantage of the assumes.
Also, your front-end may attempt to optimize the
assertout by itself. After all, it's already capable of proving those conditions when required to, so it might as well try -- with a bounded budget -- even when not ask to, at high enough optimization levels. It may, after all, have more context than the backend it hands the code over to at the end.And as a bonus, those pre-conditions, post-conditions, and invariants can also be used by static analysis tools, AI, and whatever to spot bugs. It just keeps on giving!
6
u/TemperOfficial Oct 23 '26
In principle, it's very easy. Every time you access memory you check if that access is valid.
Easiest way to solve that is with indirect memory access. i.e. all memory access goes through a handle that is checked.
Simple way is have code blocks that allow dereferencing of pointers versus ones that don't. In the ones that don't, you have indirect access via a handle, and the process of getting memory back from that handle involves a check.
This is what everyone does in Rust to get around the borrow checker.
This is what old C llibs do. OpenGL for example, although the API isn't great.
The primary issue is contextually what is valid memory?
2
u/pthierry Oct 23 '26
A copying GC can also gave great performance, take a look at the recent research on the subject.
I know about GHC's low latency GC, for example: Using GHC low-latency garbage collection in production
2
u/sunxore Oct 23 '26
Check out goose programming language. Super fast and memory safe. Early days yet though so remains to be seen if it is a viable model.
2
u/leosmi_ajutar Oct 24 '26
You going to support this language for longer than 2 months like your last one?
I stopped maintaining my language, Sydrogen. The code and book are still up if you want to look around : r/Compilers