> remember that for compilers which emit machine code, like roc and rustc, doing memory-unsafe things is a big part of the job
I don't really think that this is true, in the way that it's written.
I think that for the hot binary patching / code reloading features, yes, that is going to need unsafe. But for regular old "producing an executable" compilation? Emitting machine code isn't the part that requires unsafe. The language's runtime is a more likely site to find unsafe.
> I think that for the hot binary patching / code reloading features, yes, that is going to need unsafe. But for regular old "producing an executable" compilation? Emitting machine code isn't the part that requires unsafe. The language's runtime is a more likely site to find unsafe.
Agreed! Emitting machine code is not unsafe, since it's just writing bytes down - it's only once you execute that machine code that there's potentially unsafety. The reason I said "a big part of the job" is that in practice a lot of compilers both emit machine code and execute it - but you're totally right that it's not a requirement that a compiler do both.
In addition to the examples you gave (hot binary patching/code reloading, language runtime, etc.), others would be things like evaluating userspace code at compile time (e.g. const fn in Rust, or in Roc any expression that could be hoisted to the top level), running tests and inspecting their output to decide what to display to the user, etc.
Those are the types of things I had in mind when I wrote that.
I am disappointed you're downvoted, Richard. This is a fine reply, and I hope you know that a minor quibble with a single line in the post doesn't mean that I think it's a bad one overall. (EDIT: a few minutes later, the parent comment is no longer grey.)
I also think it's a good thing that you wrote the post in general, when I saw it pop up I was like "oh, of course, this post should exist!" I'm surprised I didn't think about it earlier.
> evaluating userspace code at compile time
Usually this would be done via an interpreter, so I'm not sure that it really requires unsafe either. If you are literally executing machine code, sure, but const fn in Rust and constexpr in C++ and many other languages do not do that, as it causes a number of problems (for example, cross-compilation).
Also a good point! TIL that Rust and C++ use interpreters for const, although of course that wouldn't work for running tests. Then again, in the specific case of Rust I believe rustc only compiles the tests and then something else like Cargo executes them. Of course, as I noted elsewhere, if rustc emits machine code and then cargo immediately executes it, there's the same opportunity for end user memory being corrupted (due to miscompilation) as if rustc and cargo shared a code base.
By the way, I thought your question was totally reasonable - my first thought reading it was "Oh yeah I wasn't trying to say that writing bytes is unsafe, I definitely should have worded that differently."
Cool, I'm not sure that people know that we know each other and have some deeper mutual understanding. :)
> although of course that wouldn't work for running tests.
Why not? Unless you mean in the cross-compilation case, in which yeah, to run the compiled tests you'd need an emulator.
> in the specific case of Rust I believe rustc only compiles the tests and then something else like Cargo executes them.
It doesn't have to be Cargo, but yes, rustc produces executables for the tests, and you have to then run them.
> there's the same opportunity for end user memory being corrupted (due to miscompilation)
I agree for sure that the safety of the outputted binary is completely distinct from the safety of the compiler itself.
I think the reason that this framing specifically (in the post and in this comment) strikes me as odd is that "requires unsafe code" sort of implies that you need to use unsafe to fix the unsafety of the outputted binary. That just isn't the case. Of course, this is a serious bug that needs to be fixed, but there's just something about "doing memory unsafe things" in this area that like, I think can be a little mis-leading, even if that's not intentional. But I am going to sit with this and think about it, regardless, because I am not sure that my gut reaction here is completely accurate.
(And, hilariously, looking over some work my agents did on my compiler last night, they fixed some mis-compilations that occurred, entirely in safe code. I bet that's also part of why I'm in this headspace at the moment, it's not like those fixes required dropping down into unsafe to fix either!)
> rustc emits machine code and then cargo immediately executes it, there's the same opportunity for end user memory being corrupted (due to miscompilation) as if rustc and cargo shared a code base.
Cause this hasn't been true for me or for anyone maybe your definition of memory being corrupted is the not same as mine.
I am not even sure what you are trying to prove with this.
I appreciate the time and effort in building stuff like Roc I don't use it but this comment and the article feel like...
Oh some guy said Zig not nice because memory safety so here, a post why memory safety doesn't exist because we have to do memory unsafe things sometimes and so everything is memory unsafe already, so maybe it doesn't matter.
I get the energy that we are going for seeing useless claims and wanting to push back but I think the article deserves a clearer part 2 where you elaborate on your thoughts about stuff maybe even get it peer reviewed a bit before posting or maybe don't I guess we could use more raw thoughts in the post AI age.
Either way I appreciate someone trying to put forward their own thoughts and explain problems with a different perspective.
> if rustc emits machine code and then cargo immediately executes it, there's the same opportunity for end user memory being corrupted (due to miscompilation) as if rustc and cargo shared a code base
Your tests run in an entirely separate process from the compiler (and from cargo). This makes it very different from memory corruption in the compiler:
- The test process can only corrupt its own memory.
- You don't need "unsafe" to run tests. Just the ability to start another process.
- If you're cross-compiling, you wouldn't even be able to run the tests on the same machine (without emulation/compatibility layers)
Does roc run tests in the same process as the compiler?
I agree that it’s not inherent to emitting machine code but I do think it reflects a different set of priorities.
In extremely high performance code you use different data structures and algorithms and change your approach to memory allocation. TigerBeetle famously does all memory allocation once on startup.
Roc is attempting to make a similar set of trade-offs in their compiler as Zig, so it makes sense that the author finds many shared patterns.
> In extremely high performance code you use different data structures and algorithms and change your approach to memory allocation.
It's worth noting that the reason Rust doesn't include support for custom memory allocation patterns like Zig does has nothing to do with memory safety. It's more of a historical accident that it just wasn't something that was prioritised early in the projects history and is now hard to change.
I do think it reflects different priorities, but one of those differences is that from my perspective, safety and performance are not inherently at odds. Yes, sometimes it is needed, but not as much as some people seem to think. Sometimes, it also means writing code in ways that communicate things to the compiler that you may not think of if you're not used to thinking in this manner.
A lot of the ways in which the zig compiler works doesn't use pointers, it uses indices. This stuff is easier to write as safe code, not less easy.
> Roc is attempting to make a similar set of trade-offs in their compiler as Zig, so it makes sense that the author finds many shared patterns.
I do think that that makes sense, but it also doesn't mean that they have to. I am doing a compiler project that takes a lot of inspiration from Zig (as my language currently inherits some major things from Zig, and I also care a lot about compiler performance) and it's written in Rust, and does not use much unsafe code (outside of the usual suspects of FFI in the runtime, etc).
I think if you interpret it charitably it means that any bug in the emitted machine code is already a likely memory-unsafe miscompilation if it is ran.
The compiler itself might be perfectly "memory safe" but the generated binary fundamentally is always at risk (besides WebAssembly I suppose).
I'm fully aware of the separation of compiler and binary, and being able to compile untrusted code safely is nice, but a perfectly safe compiler that generates vulnerable binaries isn't that much better.
In context that's clearly not what he's saying, the next sentence is this:
> Zig has more features than Rust for making memory-unsafe code work correctly, and that was the area where we wanted the most help.
Zig definitely does not have more features for successfully emitting memory-unsafe machine code than Rust does. I can emit memory-unsafe machine code from typescript if I really want to and nothing at all in the language will get in my way. So the sentence quoted above must refer to the idea that the compiler itself needs to be unsafe, which Steve is right is simply untrue.
I do think that is a good point, it's just not what the line actually says. But that's why I wasn't saying "zomg this is WRONG!!!!" but instead, trying to point out that there are subtleties here. For people who aren't as deep in the weeds in this subject, I think the details matter. But again, as I said, I like the post, this is just one thing.
I am also probably in a more pedantic mindset because, well, I'm writing a compiler in Rust, and the words as written do not resonate with me at all.
> a perfectly safe compiler that generates vulnerable binaries isn't that much better.
I do think it's much better. Eliminating classes of bugs in one component is a good thing, even if it's not every component. This is a core lesson of Rust! unsafe still exists, but going from "I don't know what is unsafe" to "only this part is unsafe" is a major improvement.
They are saying that running the compiled code is memory-unsafe when there is a compiler bug, and that’s what developers do next. The memory corruption happens in a different process.
In this respect, effectively all the compiler should be treated sort of like an unsafe region because it requires extra care to avoid memory corruption bugs.
The article is a bit confusing because they also write:
> Regardless of which process had the bug—the compiler or compiled program—in both cases the processor only did the bad thing because the compiler told it to. And in both cases the fix is the same: the compiler's code must change, since that code was what caused the memory corruption.
But yeah, I wonder what those 1,200 unsafe uses actually did?
Yeah that is definitely 1000% wrong. A compiler can do its job with totally abstract data structures. If anything would need to do unsafe stuff in memory, it would probably be a linker.
I think it's an understandable prior. Historically, "low level stuff" was near-exclusively (see my comment below about OCaml...) written in unsafe languages. Even if that wasn't always literally required, it sometimes was, and so thinking this is the case was a reasonable thing to think.
It is only relatively recently that we have gained more realistic options in these spaces, and so not fully understanding the implications, or preferring the historically normal choices, is understandable.
I'll play devil's advocate. I think emitting machine code intended to run is unsafe because you could emit unsafe machine code, which could run. It's the whole system that is either safe or not, not the individual components. If your system gets hacked by a buffer overflow in the end, nobody cares whether it was the linker that overflowed or the code emitted by the linker.
"Safe" has a very specific definition in Rust. It's not identical to the broader definition used in technical English. You can easily have safe rust code with behaviors any reasonable layperson would call unsafe, like crashing a plane. The original article, comment, and replies were using the word in the Rust sense from my reading, not the English meaning.
2. Has an objective definition, when some other forms of safety are either subjective or inter-subjective.
That said, I don't understand why your parent brought this up to you, you are talking about memory safety in your original comment here, so that's what Rust's safety is about.
This is impossible. General words like "safe" and "good" are subjective, and useless in a technical context unless you ground the discussion by giving them specific definitions. Otherwise everyone ends up talking past each other.
> It's the whole system that is either safe or not, not the individual components.
This is a core perspective disagreement. While this is true:
> If your system gets hacked by a buffer overflow in the end, nobody cares whether it was the linker that overflowed or the code emitted by the linker.
That does not mean that increasing the amount of safety in the individual components isn't helpful, because it helps minimize the above outcome, even if it will never be zero.
>ReleaseSafe catches use-after-free errors through runtime checks which panic if the program tries to use freed memory.
I don't know Zig so maybe they know something I don't, but I have seen no evidence that it catches any type of use-after-free including double-free?
While writing a blog post (below) I went through the documentation to figure out the possible runtime memory safety checks Zig can insert. The term "use-after-free" or "UaF" never occurs on that documentation page. Searching for "safety-checked" doesn't yield any related hits either.
Unless maybe they're using the DebugAllocator in release builds? Even that does not reliably surface UaF.
I as someone with writing Zig a bunch, can safely say if it does it hasn't even worked for me.
I am talking from experience from a pre-ai human mitts writing code perspective maybe Zig + LLMs do some magic.
The more I read the article the more I feel like this is just bad not sure if I should be giving it as much latitude as I have been in my prior comments.
There are other claims as well that are weirdly phrased at least.
Reads like an article written to justify some arguments they had rather than a genuine take at this point.
But I will give the benefit of doubt I enjoy weird articles, languages and share a dislike for aggressive AI-ness of all things.
The DebugAllocator catches use-after-free (at least on page-level), but at the cost of never recycling memory addresses (e.g. it eats through the virtual address space).
For higher level code, "generation-counted index handles" might be the better solution to provide temporal runtime memory safety, not part of Zig the stdlib though.
Or even better: never use dynamic memory allocation and make all lifetimes 'static' :)
as a reminder its a construct in the zig stdlib to take an arbitrary chunk of memory (could be stack, could be in the programs static space) and wrap it in an allocator interface and give that to any data structure that needs an allocator and use it as if it were just malloc/free, with a fixed memory limit and the correct memory errors.
Interesting that OCaml was flexible and expressive enough to be used as a prototype testbed but not chosen as the implementation language, especially given the maturity of both. I would be surprised if Zigs incremental builds could be meaningfully faster than dune's.
Cross compilation is great, but not mentioned in the "why Zig" section. Is memory control that crucial for a compiler?
Rust itself was originally written in OCaml, same with WASM. I'm curious about what milestone gets reached where the maintainers collectively decide to transition away.
Rust moved away from OCaml when it decided to be re-written in Rust. The post alludes to this as being a usual time for a wholesale re-write, and I'd agree.
I appreciate the insight, and on closer reading the post clearly states that realistically only Zig and Rust were ever considered anyway.
Since you're here, could you comment on the approach Rust took in their rewrite? Was it more of a straight translation like Go did when they self hosted -- similar to the recent Bun transliteration? Or were there architectural changes made along the way like this article describes with Roc?
The Rust re-write happened before I got involved. If pcwalton is around and sees this comment, maybe he can provide a more first-class account.
> Was it more of a straight translation like Go did when they self hosted -- similar to the recent Bun transliteration? Or were there architectural changes made along the way like this article describes with Roc?
From what I remember, it was a whole-sale re-write from scratch, not a transliteration. While Rust took a lot of inspiration from OCaml, especially in those days, it was different enough that I'm not sure that a more direct transliteration would have been particularly possible, though again, see above, I wasn't there, so I don't know for sure.
OCaml compiler is incredibly fast. I wonder how it'd fare with Jane Street's extensions for the borrow checker etc in OxCaml, if it's good enough for their HFT I'm sure it's good enough for a new language.
I suspect this "not a systems language" alludes only to OCaml's rather steeper learning curve and until-recently difficulty with multiple threads. I am sure it could roll just fine as a single-threaded compiler language written by a small team, which indeed, it was.
I wrote a toy Scheme implementation in OCaml by using the Camplp4 preprocessor. In benchmarks, it was faster than Gambit Scheme, which compiles through C.
OCaml has often historically been considered a language that's been appropriate to write systems tooling like compilers, runtimes, and unikernels in, even though GC'd languages were/are not often considered for such projects.
This piece would have been a lot more compelling if they had actually done science on selecting a language for compiler development. From what I can tell, they had an untested hypothesis that a low level systems language is necessary for a high performance compiler https://www.roc-lang.org/faq#self-hosted-compiler and from that concluded that their only
choice besides rust was zig.
I know from experience that this initial assumption is wrong. Compiler performance is dominated by algorithms. The fastes managed languages tend to be at worst within a factor of two for wall time on any given algorithm. Algorithmic differences can be unbounded in their performance gaps. Zig itself is a perfect counterexample to the theory that writing a compiler in a low level systems language will lead to a fast compiler. Roc seems to compile at around 15k lines per second. That is not fast. There were evidently compilers written in ml that did 3k likes per second in 1998 https://flint.cs.yale.edu/cs421/case-for-ml.html
The zig rewrite of roc looks like the author's second compiler. Compiler and language design is a skill like any other and from my vantage point, they appear to have overcommitted to an initial design at the expense of developing their higher level design skills. In my opinion, the best thing they could do for the future of roc is stop working on their current compiler and use it to write a self hosting compiler for a much smaller subset of roc. They should be able to do that in less than 10k lines of code. They might even find that their self hosting compiler is faster than their zig based bootstrap compiler for the self hosted subset of roc. If the self hosting compiler is inadequate. Now they at least have identified a smaller useful subset of roc and can experiment with different compiler implementations in 10k likes of code rather than 300k lines of code. Then they could actually test the theory of whether or not a low level language is necessary to meet whatever arbitrary compiler performance goals they have.
By self hosting, they would also discover what roc features actually matter and they would spend much more time actually writing roc code. The features that are needed to write a self hosted compiler are all features that are generally useful. By improving the self hosted compiler, they also improve downstream programs.
Your comment is very assertive, but also doesn't offer much in the way of science.
Being able to compile ML quickly in the 90s tells you little about being able to compile Roc or some other language today because the language design enforces hard constraints on the algorithms necessary to compile it and the hardware today is much more complex. It's not hard to write a fast Pascal compiler that targets a 1980s chip with shallow pipelines. But that's not the problem being solved here.
I don't know much about Roc but it looks like it's got some amount of overloading and the linked article alludes to sophisticated algorithms to avoid heap allocating closures. Those can enforce algorithmic complexity in the compiler that is essential and can't be eliminated.
Once you're at the limits of algorithmic optimization, all that's left is reducing constant factors. I've written code in many languages in different performance regimes over the years and it's certainly the case that higher level languages, especially managed memory ones, put a hard floor in terms of how low you can go when optimizing to improve those constant factors.
I have seen in real-world code where explicit control over memory layout improved performance by more than an order of magnitude. I have friends in the game industry where much of their career is this kind of work. Those people would love to live in the luxurious world you describe where all they need to do is find a sufficiently clever algorithm and all of their performance problems will disappear.
Zig's incremental builds are DEFINITELY a killer feature. In the short term, I could see why you'd make a switch to get it. But, in the medium term, can we really not expect to see this in Rust in the somewhat near future?
I want to go fast, but I don't want to go fast just to shoot my foot off.
If only somehow we could get Rust's safety with all of Zig's features and Go's runtime without GC...
I'm not sure it would ever make sense to be. That makes the assumption tons of allocations get made that don't live long, which was(maybe is still?) more common in some languages. Go is more aggressive about not heap allocating, and has tools to help you avoid them.
> n practice, Go can typically outperform Rust in throughput (using more memory), despite having a mountain of disadvantages against it in theory
This is a huge claim that disagrees with both my real-world experience and everything I've seen from artificial comparisons.
Every high performance Go system I've worked on has quickly reached the point where we're optimizing memory management and doing things that would have been explicit in a non-GC language like Rust anyway.
The Go runtime is amazingly optimized, but it comes with overhead over doing the same work directly in a lower level language.
I think this is interesting and warrants explanation. There are cases where a GC can be faster (sort of, Arenas get you most of the gains) but "the most sophisticated scheduling engine in the world" should be easy to at least partially support.
> It's literally the most sophisticated scheduling engine in the world.
That seems unlikely regardless of how good it is. This is a domain where state-of-the-art research is not in the public literature. Scheduling is an AI-complete problem.
Erlang's scheduler is not sophisticated, which is what makes it AWESOME.
but yeah. i would be surprised if the JVM's scheduler is not more sophisticated than go's if for no other reason than it has way more knobs you can tune. you know they put that knob in there because someone (probably Google cough cough) asked for it
Instead of waiting for faster compiler in Rust, how about from the other direction, adding some kind of borrow checker to Zig? That sounds more within reach and practically achievable, possibly even in userland.
It's impossible to add a borrow checker to any existing language.
The reason Rust has a working borrow checker is because every part of the language from structs, enum, traits, generics and all the way to the syntax itself has been designed to support lifetimes and borrow checking.
It's is not something you can just tack on to an existing language without fundamentally changing it.
I wouldn't say it's impossible, rather un-ergonomic. TypeScript can add type information to ordinary JavaScript code via JSDoc comments; the result can both be executed as ordinary JavaScript as-is and type-checked with TypeScript. But it's a huge pain to try to write (and maintain) everything that way, it was supported as a hack to help migrate legacy codebases. You could probably take a similar "the lifetimes are embedded in comments" approach with other languages, and the result would be similarly un-ergonomic.
no. You don't need private fields. All you have to do is analyze the code, harness the compiler to generate a time-dependent data dependency graph, and map allocation/frees/uses, if you can 'color' branches where data are shared you can also track and check to see there isn't an aliasing violation too.
it is easy to patch the zig compiler to enable this this (export the code graph; about 50 LOC). The analysis is much much harder to get right.
You may have missed the point here. You could add a comment to the struct field that marks the field as private, and build a TypeScript/JSDoc analogue that analyzes all accesses to the field and fails if it finds accesses from functions that aren't part of the struct that owns the field. You don't even need a comment on the field - you could copy Go's convention, add a comment to the struct definition marking it as "follows Go convention", and then fail any access from outside the struct to a field that starts with a lower-case character.
It doesn't prevent you from ignoring that tool and writing Zig code that imports the struct and accesses the field. It is, of course, not part of the Zig language itself. But if you adopted a tool like that, it would be your responsibility to run it across-the-board and pay attention to the results - same as how it is your responsibility to pay attention to the results if you added those JSDoc comments.
empirically untrue. several projects exist that bolt on extra safety to unsafe languages or unsafe parts of language. SeL4 for C, MIRI for rust unsafe. i guess ada/spark for ada too, is the OG, spark being added to ada 4 years after its first release
> It's impossible to add a borrow checker to any existing language.
Why do you say that. Have you tried and failed? It seems to be possible to add a borrow checker to zig, just as you can add MIRI to rust to get extra safety in unsafe blocks.
> how about from the other direction, adding some kind of borrow checker to Zig? That sounds more within reach and practically achievable, possibly even in userland.
It's doable, and as static analysis. see sibling comment.
One thing I wish Rust would improve over time is the builds. Its one of the biggest sources of wasted storage space on all my computers, builds a ton of libraries can take tens of gigs, it adds up very quickly. Not sure what the best solution is, one I found is to set the global build folder so dependencies get reused across projects, but imho it should be an OOTB default behavior whatever the real solution should be.
We are trading away disk space for faster builds. We could make them faster in some cases by using even more...
On the other hand, it would be good to garbage collect those caches. We are wrapping up work on a new layout for intermediate build artifacts that will make it easier to GC them.
Sounds like what I was thinking, that or for third party deps to go into the same temp folder, and anything not accessed in over a week, or so just gets auto wiped by rustc / cargo build process?
Rust isn't great, and it shouldn't be a surprised since it's designed after npm. However one metric where nodes_modules is still worse for me is the sheer number of small files in it.
Having nearly one million files in nodes_modules isn't that unusual. The problem is that on most common file systems the minimum allocation is usually at least 4KB. So even if the actual data is less than 500MB, you end up with 4GB disk space used/wasted.
I wish ext4 had a feature to mark a file as "atomic" where it would allocate all atomic files in a long run, without room for expansion, and I suppose with very inefficient compaction upon deletion, but without any padding bytes.
The compiler is one of the most significant trust boundaries we have. Its decisions can intentionally or unintentionally create vulnerabilities in programs compiled by the compiler, which means that if you can compromise a compiler you can compromise everything downstream.
Unsafe memory access in a compiler can be exploited in order to hijack the compiler itself (this is reported regularly in production compilers), allowing the attacker to then insert arbitrary code into compiled binaries. Not everything that a compiler absorbs from its environment is meant to be treated as source to be compiled, and in a memory unsafe compiler any of that input can silently turn into machine code in the compiled binary if an attacker is able to exploit the memory safety bug and hijack the compiler.
Zig is a pre-1.0 language while Rust is post-1.0. This alone is settles which one to pick for may developers. The library support is probably favours Rust too. Rust build times are much slower than Zig, I get that, but I rarely optimize software for build times.
Zig is not pre-1.0 because it’s not ready for production (bugs or missing features), it’s pre-1.0 because they want to be able to make breaking language changes.
Nowadays when you can just point an agent at release notes and have it update everything, I actually prefer not having to wait through rare major releases to get new language features.
> Zig is not pre-1.0 because it’s not ready for production (bugs or missing features), it’s pre-1.0 because they want to be able to make breaking language changes.
This is a solved problem in other projects. Either use the version numbers as intended and bump the major version number on breaking changes, or use Rust-style editions to opt in to the newer versions of the changes.
Calling a project production-ready but keeping the version number below 1.0 and saying breaking changes are expected is a tired game. We've seen it backfire across a number of language projects like Elm, where the exact same claim was used to both encourage people to use it and then blame them when it backfired.
If it's production ready, go to 1.0 and then follow semver for breaking changes. I don't care if we get to Zig v73.2.0 as a result. At least we can see from a glance which versions need to be checked for breaking changes.
languages ideally should not have breaking changes ever.
on the other hand, a language with frequent breaking changes should not be considered production ready.
people are of course free to live on the edge, and if someone decided that zig is good enough and they are not bothered by breaking changes then they are free to use it for their production system, but that doesn't mean it's ready for everyone. so i prefer the zig approach.
> Nowadays when you can just point an agent at release notes and have it update everything
Except that means that not only you lose compiler bugfixes, you also pretty much has no access to the ecosystem. For most production codebases, this is a deal breaker.
I invite you to read the release notes and see for yourself the types of breaking changes we’re talking about.
To me it is not much different from Lua, which despite being on 5.x for decades, makes breaking changes on minor releases (because it predates SemVer).
I also don’t see it being much different from any other language or language runtime that has a major release every year.
I am not sure, but there might be a bug in their pattern matching example.
What happens if 'verb' is "GET" and 'path' is "/users/1234/posts/1234/extra_path/and/more/"? Will 'post_id' become "extra_path/and/more/"?
I tried running it in the sandbox, and it does indeed seem to buggily result in:
"Post ID: 1234/extra_path/and/more"
I suspect that the reason it is behaving like it is, is due to how it handles characters in the string literal. The example program exploits that only the slashes present in the string literal pattern are matched, to enable matching on 'page' having slashes. But then in the nested 'match', it forgot to account for any possible extra slashes.
Nitpicking end.
I have not read the whole post yet, but the pattern matching not requiring any allocations, seems very nice. The string literal patterns also seem interesting, though I am not completely sold on them, also as per the above possible bug. It seems really clean in some ways, but the specific semantics, I am not fully sure about. Maybe it is excellent, and is so clean and concise that it is overall less bug-prone than alternatives in other programming languages. I do not know.
Irrespective to the technical merits of both language, moving from a stable language to a pre-1.0 one that just lost his most popular open source project is a wild move.
> that just lost his most popular open source project
As they state in the article, they started the migration a year and a half ago, something that happened a few weeks back would never come into the decision making process.
While I'm a rust enthusiast, I do agree that certain languages lend themselves well to particular domains. So a rewrite from Rust to something better suited is fine by me. In fact, while I do work on a rust project, I would not have and still would not recommend it as the choice for that particular project.
That being said, I had to do some double takes while reading this.
I feel that it's a bit weird to compare a rather well tested 7 (?) year old rust implementation with a brand new not yet released less than a year old Zig implementation. Without that context, this looks like a bad comparison for rust, when it is in fact the complete opposite.
The swiftness of the Zig compilere here is insane, and would would very much shift my recommendation of Rust if it got to similar speeds.
That being said, I do find it funny that currently, the compilation speed is actually worse on Zig than Rust, despite Zig (anonymous commenters at least tbf) claiming the opposite for years.
How did you eventually discover the 35 ms figure for Roc? Did you have to temporarily update the codebase to 0.17?
Nothing negative here. I did play around with implementing a scripting language in this DOD-ish, index-based paradigm and yeah, it is neat.
I was thinking that it might be possible to do resumable computation across the network like this (in the context of frontend frameworks "resuming" UIs), but ultimately I have no use for this so just the experience itself was enough.
One note here is that it does tend to break completely if non-pointer-free data is introduced. It seems like it's either all or nothing.
> In fact, while I do work on a rust project, I would not have and still would not recommend it as the choice for that particular project.
wondering what type of project is that? I think besides some very embedded projects with very little memory where you need C/assembly, rust is good enough for all kind of projects..
I work both on a pretty much bog-standard web (GraphQL) backend and the frontend that uses it. We switched over from Apollo on node to async-graphql on Rust.
The runtime performance is much better, but the compiler time performance is terrible. To be fair, this is mostly the fault of async-graphql, but that doesn't really matter all that much. For example, it's not uncommon for a single character SQL query change to trigger over a minute long incremental rebuild.
The rust compiler is just choking on the number of generics and codegenned functions.
I've personally looked at how to improve this, but short of breaking up the type graph using federation, nothing can help. Not even cranelift makes a noticeable dent.
Additionally, the team started off composed by a bunch of TypeScript/React/Node developers, so mistakes were made along the way.
Honestly, I would have recommended to just use C#.
That's not to say that I don't think Rust can work for web development. We have some (GraphQL-less) services where Rust is a great fit. Just maybe shouldn't have been the default. That or give up graphql ...
For whatever it's worth, I share some of your async-graphql woes, though I haven't investigated things deeply enough to have strong opinions about what to do instead.
I don't even know what Zig is but I've seen this topic come up so many times on this site that I'm starting to think the people who are actually doing this are unsure themselves whether it's a good idea or not.
I think this is a fine post. But one comment:
> remember that for compilers which emit machine code, like roc and rustc, doing memory-unsafe things is a big part of the job
I don't really think that this is true, in the way that it's written.
I think that for the hot binary patching / code reloading features, yes, that is going to need unsafe. But for regular old "producing an executable" compilation? Emitting machine code isn't the part that requires unsafe. The language's runtime is a more likely site to find unsafe.
> I think that for the hot binary patching / code reloading features, yes, that is going to need unsafe. But for regular old "producing an executable" compilation? Emitting machine code isn't the part that requires unsafe. The language's runtime is a more likely site to find unsafe.
Agreed! Emitting machine code is not unsafe, since it's just writing bytes down - it's only once you execute that machine code that there's potentially unsafety. The reason I said "a big part of the job" is that in practice a lot of compilers both emit machine code and execute it - but you're totally right that it's not a requirement that a compiler do both.
In addition to the examples you gave (hot binary patching/code reloading, language runtime, etc.), others would be things like evaluating userspace code at compile time (e.g. const fn in Rust, or in Roc any expression that could be hoisted to the top level), running tests and inspecting their output to decide what to display to the user, etc.
Those are the types of things I had in mind when I wrote that.
I am disappointed you're downvoted, Richard. This is a fine reply, and I hope you know that a minor quibble with a single line in the post doesn't mean that I think it's a bad one overall. (EDIT: a few minutes later, the parent comment is no longer grey.)
I also think it's a good thing that you wrote the post in general, when I saw it pop up I was like "oh, of course, this post should exist!" I'm surprised I didn't think about it earlier.
> evaluating userspace code at compile time
Usually this would be done via an interpreter, so I'm not sure that it really requires unsafe either. If you are literally executing machine code, sure, but const fn in Rust and constexpr in C++ and many other languages do not do that, as it causes a number of problems (for example, cross-compilation).
Also a good point! TIL that Rust and C++ use interpreters for const, although of course that wouldn't work for running tests. Then again, in the specific case of Rust I believe rustc only compiles the tests and then something else like Cargo executes them. Of course, as I noted elsewhere, if rustc emits machine code and then cargo immediately executes it, there's the same opportunity for end user memory being corrupted (due to miscompilation) as if rustc and cargo shared a code base.
By the way, I thought your question was totally reasonable - my first thought reading it was "Oh yeah I wasn't trying to say that writing bytes is unsafe, I definitely should have worded that differently."
Cool, I'm not sure that people know that we know each other and have some deeper mutual understanding. :)
> although of course that wouldn't work for running tests.
Why not? Unless you mean in the cross-compilation case, in which yeah, to run the compiled tests you'd need an emulator.
> in the specific case of Rust I believe rustc only compiles the tests and then something else like Cargo executes them.
It doesn't have to be Cargo, but yes, rustc produces executables for the tests, and you have to then run them.
> there's the same opportunity for end user memory being corrupted (due to miscompilation)
I agree for sure that the safety of the outputted binary is completely distinct from the safety of the compiler itself.
I think the reason that this framing specifically (in the post and in this comment) strikes me as odd is that "requires unsafe code" sort of implies that you need to use unsafe to fix the unsafety of the outputted binary. That just isn't the case. Of course, this is a serious bug that needs to be fixed, but there's just something about "doing memory unsafe things" in this area that like, I think can be a little mis-leading, even if that's not intentional. But I am going to sit with this and think about it, regardless, because I am not sure that my gut reaction here is completely accurate.
(And, hilariously, looking over some work my agents did on my compiler last night, they fixed some mis-compilations that occurred, entirely in safe code. I bet that's also part of why I'm in this headspace at the moment, it's not like those fixes required dropping down into unsafe to fix either!)
I would like to understand this more,
> rustc emits machine code and then cargo immediately executes it, there's the same opportunity for end user memory being corrupted (due to miscompilation) as if rustc and cargo shared a code base.
Cause this hasn't been true for me or for anyone maybe your definition of memory being corrupted is the not same as mine.
I am not even sure what you are trying to prove with this.
I appreciate the time and effort in building stuff like Roc I don't use it but this comment and the article feel like...
Oh some guy said Zig not nice because memory safety so here, a post why memory safety doesn't exist because we have to do memory unsafe things sometimes and so everything is memory unsafe already, so maybe it doesn't matter.
I get the energy that we are going for seeing useless claims and wanting to push back but I think the article deserves a clearer part 2 where you elaborate on your thoughts about stuff maybe even get it peer reviewed a bit before posting or maybe don't I guess we could use more raw thoughts in the post AI age.
Either way I appreciate someone trying to put forward their own thoughts and explain problems with a different perspective.
> if rustc emits machine code and then cargo immediately executes it, there's the same opportunity for end user memory being corrupted (due to miscompilation) as if rustc and cargo shared a code base
Your tests run in an entirely separate process from the compiler (and from cargo). This makes it very different from memory corruption in the compiler:
- The test process can only corrupt its own memory.
- You don't need "unsafe" to run tests. Just the ability to start another process.
- If you're cross-compiling, you wouldn't even be able to run the tests on the same machine (without emulation/compatibility layers)
Does roc run tests in the same process as the compiler?
Many people try to twist the fact memory safe languages have unsafe code blocks to make the pivot that why bother.
It is like someone arguing that since they always bump the head somehow while wearing seatbelts, then they are only a nuisance and should not be used.
I agree that it’s not inherent to emitting machine code but I do think it reflects a different set of priorities.
In extremely high performance code you use different data structures and algorithms and change your approach to memory allocation. TigerBeetle famously does all memory allocation once on startup.
Roc is attempting to make a similar set of trade-offs in their compiler as Zig, so it makes sense that the author finds many shared patterns.
> In extremely high performance code you use different data structures and algorithms and change your approach to memory allocation.
It's worth noting that the reason Rust doesn't include support for custom memory allocation patterns like Zig does has nothing to do with memory safety. It's more of a historical accident that it just wasn't something that was prioritised early in the projects history and is now hard to change.
No disagreement in principle; in practice taking that approach in Zig is safer than in Rust, because in Rust it’s “all or nothing.”
I do think it reflects different priorities, but one of those differences is that from my perspective, safety and performance are not inherently at odds. Yes, sometimes it is needed, but not as much as some people seem to think. Sometimes, it also means writing code in ways that communicate things to the compiler that you may not think of if you're not used to thinking in this manner.
A lot of the ways in which the zig compiler works doesn't use pointers, it uses indices. This stuff is easier to write as safe code, not less easy.
> Roc is attempting to make a similar set of trade-offs in their compiler as Zig, so it makes sense that the author finds many shared patterns.
I do think that that makes sense, but it also doesn't mean that they have to. I am doing a compiler project that takes a lot of inspiration from Zig (as my language currently inherits some major things from Zig, and I also care a lot about compiler performance) and it's written in Rust, and does not use much unsafe code (outside of the usual suspects of FFI in the runtime, etc).
I think if you interpret it charitably it means that any bug in the emitted machine code is already a likely memory-unsafe miscompilation if it is ran.
The compiler itself might be perfectly "memory safe" but the generated binary fundamentally is always at risk (besides WebAssembly I suppose).
I'm fully aware of the separation of compiler and binary, and being able to compile untrusted code safely is nice, but a perfectly safe compiler that generates vulnerable binaries isn't that much better.
In context that's clearly not what he's saying, the next sentence is this:
> Zig has more features than Rust for making memory-unsafe code work correctly, and that was the area where we wanted the most help.
Zig definitely does not have more features for successfully emitting memory-unsafe machine code than Rust does. I can emit memory-unsafe machine code from typescript if I really want to and nothing at all in the language will get in my way. So the sentence quoted above must refer to the idea that the compiler itself needs to be unsafe, which Steve is right is simply untrue.
I do think that is a good point, it's just not what the line actually says. But that's why I wasn't saying "zomg this is WRONG!!!!" but instead, trying to point out that there are subtleties here. For people who aren't as deep in the weeds in this subject, I think the details matter. But again, as I said, I like the post, this is just one thing.
I am also probably in a more pedantic mindset because, well, I'm writing a compiler in Rust, and the words as written do not resonate with me at all.
> a perfectly safe compiler that generates vulnerable binaries isn't that much better.
I do think it's much better. Eliminating classes of bugs in one component is a good thing, even if it's not every component. This is a core lesson of Rust! unsafe still exists, but going from "I don't know what is unsafe" to "only this part is unsafe" is a major improvement.
The section this came from was talking specifically about usages of `unsafe` in the compiler code.
It's not about the memory safety of the resulting binary.
That line confused me, too. What parts of their compiler require memory-unsafe operations to produce machine code?
They are saying that running the compiled code is memory-unsafe when there is a compiler bug, and that’s what developers do next. The memory corruption happens in a different process.
In this respect, effectively all the compiler should be treated sort of like an unsafe region because it requires extra care to avoid memory corruption bugs.
That's not what it says at all. The section we're talking about is for the compiler and emitting machine code
> we ended up with about 1,200 uses of unsafe
> remember that for compilers which emit machine code, like roc and rustc, doing memory-unsafe things is a big part of the job
Anywhere talking about the `unsafe` keyword is within the Rust code.
The article is a bit confusing because they also write:
> Regardless of which process had the bug—the compiler or compiled program—in both cases the processor only did the bad thing because the compiler told it to. And in both cases the fix is the same: the compiler's code must change, since that code was what caused the memory corruption.
But yeah, I wonder what those 1,200 unsafe uses actually did?
Yeah that is definitely 1000% wrong. A compiler can do its job with totally abstract data structures. If anything would need to do unsafe stuff in memory, it would probably be a linker.
> probably be a linker
I don't think that's any different either. The core job of linking isn't particularly unsafe.
(Unless, similarly, you're doing the hot reloading stuff)
I've noticed that people equate "low level stuff" with unsafe, regardless of whether it's contextually justified.
I think it's an understandable prior. Historically, "low level stuff" was near-exclusively (see my comment below about OCaml...) written in unsafe languages. Even if that wasn't always literally required, it sometimes was, and so thinking this is the case was a reasonable thing to think.
It is only relatively recently that we have gained more realistic options in these spaces, and so not fully understanding the implications, or preferring the historically normal choices, is understandable.
I'll play devil's advocate. I think emitting machine code intended to run is unsafe because you could emit unsafe machine code, which could run. It's the whole system that is either safe or not, not the individual components. If your system gets hacked by a buffer overflow in the end, nobody cares whether it was the linker that overflowed or the code emitted by the linker.
That would mean no language can ever be considered safe, because any language can emit bytes to a file that will later be executed.
Correct. Safety is a system property, not a language property. Calling a language safe is about as sensible as calling a metal alloy unsinkable.
"Safe" has a very specific definition in Rust. It's not identical to the broader definition used in technical English. You can easily have safe rust code with behaviors any reasonable layperson would call unsafe, like crashing a plane. The original article, comment, and replies were using the word in the Rust sense from my reading, not the English meaning.
Then that's equivocation. Why do we want a very specific form of safety instead of wanting safety in general?
Memory safety is:
1. Foundational for other forms of safety
2. Has an objective definition, when some other forms of safety are either subjective or inter-subjective.
That said, I don't understand why your parent brought this up to you, you are talking about memory safety in your original comment here, so that's what Rust's safety is about.
> safety in general
This is impossible. General words like "safe" and "good" are subjective, and useless in a technical context unless you ground the discussion by giving them specific definitions. Otherwise everyone ends up talking past each other.
> Why do we want a very specific form of safety instead of wanting safety in general?
Because a “very specific form of safety” is a useful tool in achieving “safety in general”
Because a “very specific form of safety” is tractable for a compiler and language runtime to achieve, “safety in general” isn’t
The only safe program by this measure is the one that's never ran.
> It's the whole system that is either safe or not, not the individual components.
This is a core perspective disagreement. While this is true:
> If your system gets hacked by a buffer overflow in the end, nobody cares whether it was the linker that overflowed or the code emitted by the linker.
That does not mean that increasing the amount of safety in the individual components isn't helpful, because it helps minimize the above outcome, even if it will never be zero.
Perhaps the parent meant dynamic linker.
Agreed, that’s disturbingly incorrect.
If anything, compilers are perfect models of trees and well formed programs.
>ReleaseSafe catches use-after-free errors through runtime checks which panic if the program tries to use freed memory.
I don't know Zig so maybe they know something I don't, but I have seen no evidence that it catches any type of use-after-free including double-free?
While writing a blog post (below) I went through the documentation to figure out the possible runtime memory safety checks Zig can insert. The term "use-after-free" or "UaF" never occurs on that documentation page. Searching for "safety-checked" doesn't yield any related hits either.
Unless maybe they're using the DebugAllocator in release builds? Even that does not reliably surface UaF.
https://landaire.net/memory-safety-by-default-is-non-negotia...
I as someone with writing Zig a bunch, can safely say if it does it hasn't even worked for me.
I am talking from experience from a pre-ai human mitts writing code perspective maybe Zig + LLMs do some magic.
The more I read the article the more I feel like this is just bad not sure if I should be giving it as much latitude as I have been in my prior comments.
There are other claims as well that are weirdly phrased at least.
Reads like an article written to justify some arguments they had rather than a genuine take at this point.
But I will give the benefit of doubt I enjoy weird articles, languages and share a dislike for aggressive AI-ness of all things.
I believe you are correct.
I think ReleaseSafe just adds bound checking and panics on unreachable code.
I don't think Zig offers any temporal memory safety.
The DebugAllocator catches use-after-free (at least on page-level), but at the cost of never recycling memory addresses (e.g. it eats through the virtual address space).
https://ziglang.org/documentation/master/std/#src/std/heap/d...
For higher level code, "generation-counted index handles" might be the better solution to provide temporal runtime memory safety, not part of Zig the stdlib though.
Or even better: never use dynamic memory allocation and make all lifetimes 'static' :)
>The DebugAllocator catches use-after-free (at least on page-level)
To clarify, is that to say that you have to use the `std.heap.page_allocator` as its backing allocator?
as a reminder its a construct in the zig stdlib to take an arbitrary chunk of memory (could be stack, could be in the programs static space) and wrap it in an allocator interface and give that to any data structure that needs an allocator and use it as if it were just malloc/free, with a fixed memory limit and the correct memory errors.
Interesting that OCaml was flexible and expressive enough to be used as a prototype testbed but not chosen as the implementation language, especially given the maturity of both. I would be surprised if Zigs incremental builds could be meaningfully faster than dune's.
Cross compilation is great, but not mentioned in the "why Zig" section. Is memory control that crucial for a compiler?
Rust itself was originally written in OCaml, same with WASM. I'm curious about what milestone gets reached where the maintainers collectively decide to transition away.
Rust moved away from OCaml when it decided to be re-written in Rust. The post alludes to this as being a usual time for a wholesale re-write, and I'd agree.
I appreciate the insight, and on closer reading the post clearly states that realistically only Zig and Rust were ever considered anyway.
Since you're here, could you comment on the approach Rust took in their rewrite? Was it more of a straight translation like Go did when they self hosted -- similar to the recent Bun transliteration? Or were there architectural changes made along the way like this article describes with Roc?
The Rust re-write happened before I got involved. If pcwalton is around and sees this comment, maybe he can provide a more first-class account.
> Was it more of a straight translation like Go did when they self hosted -- similar to the recent Bun transliteration? Or were there architectural changes made along the way like this article describes with Roc?
From what I remember, it was a whole-sale re-write from scratch, not a transliteration. While Rust took a lot of inspiration from OCaml, especially in those days, it was different enough that I'm not sure that a more direct transliteration would have been particularly possible, though again, see above, I wasn't there, so I don't know for sure.
One of the primary goals for the Roc project is compiler speed. I presume OCaml is out of the running because it's not a systems language.
OCaml compiler is incredibly fast. I wonder how it'd fare with Jane Street's extensions for the borrow checker etc in OxCaml, if it's good enough for their HFT I'm sure it's good enough for a new language.
I suspect this "not a systems language" alludes only to OCaml's rather steeper learning curve and until-recently difficulty with multiple threads. I am sure it could roll just fine as a single-threaded compiler language written by a small team, which indeed, it was.
I wrote a toy Scheme implementation in OCaml by using the Camplp4 preprocessor. In benchmarks, it was faster than Gambit Scheme, which compiles through C.
Depends on the beholder.
Unix system programming in OCaml
https://ocaml.github.io/ocamlunix/
https://mirage.io/
OCaml has often historically been considered a language that's been appropriate to write systems tooling like compilers, runtimes, and unikernels in, even though GC'd languages were/are not often considered for such projects.
They are considered in many research labs since Xerox, unfortunately there are still too much anti-GC religion among mainstream devs.
This piece would have been a lot more compelling if they had actually done science on selecting a language for compiler development. From what I can tell, they had an untested hypothesis that a low level systems language is necessary for a high performance compiler https://www.roc-lang.org/faq#self-hosted-compiler and from that concluded that their only choice besides rust was zig.
I know from experience that this initial assumption is wrong. Compiler performance is dominated by algorithms. The fastes managed languages tend to be at worst within a factor of two for wall time on any given algorithm. Algorithmic differences can be unbounded in their performance gaps. Zig itself is a perfect counterexample to the theory that writing a compiler in a low level systems language will lead to a fast compiler. Roc seems to compile at around 15k lines per second. That is not fast. There were evidently compilers written in ml that did 3k likes per second in 1998 https://flint.cs.yale.edu/cs421/case-for-ml.html
The zig rewrite of roc looks like the author's second compiler. Compiler and language design is a skill like any other and from my vantage point, they appear to have overcommitted to an initial design at the expense of developing their higher level design skills. In my opinion, the best thing they could do for the future of roc is stop working on their current compiler and use it to write a self hosting compiler for a much smaller subset of roc. They should be able to do that in less than 10k lines of code. They might even find that their self hosting compiler is faster than their zig based bootstrap compiler for the self hosted subset of roc. If the self hosting compiler is inadequate. Now they at least have identified a smaller useful subset of roc and can experiment with different compiler implementations in 10k likes of code rather than 300k lines of code. Then they could actually test the theory of whether or not a low level language is necessary to meet whatever arbitrary compiler performance goals they have.
By self hosting, they would also discover what roc features actually matter and they would spend much more time actually writing roc code. The features that are needed to write a self hosted compiler are all features that are generally useful. By improving the self hosted compiler, they also improve downstream programs.
Your comment is very assertive, but also doesn't offer much in the way of science.
Being able to compile ML quickly in the 90s tells you little about being able to compile Roc or some other language today because the language design enforces hard constraints on the algorithms necessary to compile it and the hardware today is much more complex. It's not hard to write a fast Pascal compiler that targets a 1980s chip with shallow pipelines. But that's not the problem being solved here.
I don't know much about Roc but it looks like it's got some amount of overloading and the linked article alludes to sophisticated algorithms to avoid heap allocating closures. Those can enforce algorithmic complexity in the compiler that is essential and can't be eliminated.
Once you're at the limits of algorithmic optimization, all that's left is reducing constant factors. I've written code in many languages in different performance regimes over the years and it's certainly the case that higher level languages, especially managed memory ones, put a hard floor in terms of how low you can go when optimizing to improve those constant factors.
I have seen in real-world code where explicit control over memory layout improved performance by more than an order of magnitude. I have friends in the game industry where much of their career is this kind of work. Those people would love to live in the luxurious world you describe where all they need to do is find a sufficiently clever algorithm and all of their performance problems will disappear.
Zig's incremental builds are DEFINITELY a killer feature. In the short term, I could see why you'd make a switch to get it. But, in the medium term, can we really not expect to see this in Rust in the somewhat near future?
I want to go fast, but I don't want to go fast just to shoot my foot off.
If only somehow we could get Rust's safety with all of Zig's features and Go's runtime without GC...
That's what I'm working on building [=
This is being worked on: https://rust-lang.github.io/rust-project-goals/2026/roadmap-...
Most of the goals on this page are targeted for this year.
Rust's compile times will get faster long before Zig gets safer.
I'm pretty sure Zig has no plans to ever become safe - by any sane sense of the word - so, yes, I would expect...
zig does have plans to give access to IRs when stable so adding a borrow checker to zig will be even easier than it is now
Layperson here: what is special about Go's runtime, aside from the GC?
Is the Go GC that special? Is it even generational yet?
I'm not sure it would ever make sense to be. That makes the assumption tons of allocations get made that don't live long, which was(maybe is still?) more common in some languages. Go is more aggressive about not heap allocating, and has tools to help you avoid them.
Chief design goals were radically easy concurrency and speed of compilation.
Speed of compilation feels like a distant second in terms of goals given the weird new generic features they keep adding..
I was fine with basic generics they complicated it quite a bit much for my liking.
Goroutines?
It's literally the most sophisticated scheduling engine in the world.
In practice, Go can typically outperform Rust in throughput (using more memory), despite having a mountain of disadvantages against it in theory.
That's how good the Go scheduler/runtime is.
> n practice, Go can typically outperform Rust in throughput (using more memory), despite having a mountain of disadvantages against it in theory
This is a huge claim that disagrees with both my real-world experience and everything I've seen from artificial comparisons.
Every high performance Go system I've worked on has quickly reached the point where we're optimizing memory management and doing things that would have been explicit in a non-GC language like Rust anyway.
The Go runtime is amazingly optimized, but it comes with overhead over doing the same work directly in a lower level language.
This is the first I've heard anyone claim higher throughput for Go than Rust. Any articles you'd point to to learn more?
I think one of the few performance benefits with a GC is that you can defer allocations. You can do that in Rust too though.
I think this is interesting and warrants explanation. There are cases where a GC can be faster (sort of, Arenas get you most of the gains) but "the most sophisticated scheduling engine in the world" should be easy to at least partially support.
> It's literally the most sophisticated scheduling engine in the world.
That seems unlikely regardless of how good it is. This is a domain where state-of-the-art research is not in the public literature. Scheduling is an AI-complete problem.
What benchmarks are you referring to?
Rust itself doesn't have a scheduler of course, I assume this is comparing against tokio or one of the other async executors?
What a joke, ignoring Erlang, and the custom schedulers from JVM and CLR runtimes.
Erlang's scheduler is not sophisticated, which is what makes it AWESOME.
but yeah. i would be surprised if the JVM's scheduler is not more sophisticated than go's if for no other reason than it has way more knobs you can tune. you know they put that knob in there because someone (probably Google cough cough) asked for it
Instead of waiting for faster compiler in Rust, how about from the other direction, adding some kind of borrow checker to Zig? That sounds more within reach and practically achievable, possibly even in userland.
It's impossible to add a borrow checker to any existing language.
The reason Rust has a working borrow checker is because every part of the language from structs, enum, traits, generics and all the way to the syntax itself has been designed to support lifetimes and borrow checking.
It's is not something you can just tack on to an existing language without fundamentally changing it.
I wouldn't say it's impossible, rather un-ergonomic. TypeScript can add type information to ordinary JavaScript code via JSDoc comments; the result can both be executed as ordinary JavaScript as-is and type-checked with TypeScript. But it's a huge pain to try to write (and maintain) everything that way, it was supported as a hack to help migrate legacy codebases. You could probably take a similar "the lifetimes are embedded in comments" approach with other languages, and the result would be similarly un-ergonomic.
That is possible (clang has experimental lifetime annotations support), but that is not enough to guarantee memory safety.
As a simple example, Zig has no private fields. That makes encapsulating any unsafety impossible.
no. You don't need private fields. All you have to do is analyze the code, harness the compiler to generate a time-dependent data dependency graph, and map allocation/frees/uses, if you can 'color' branches where data are shared you can also track and check to see there isn't an aliasing violation too.
it is easy to patch the zig compiler to enable this this (export the code graph; about 50 LOC). The analysis is much much harder to get right.
> Zig has no private fields
You may have missed the point here. You could add a comment to the struct field that marks the field as private, and build a TypeScript/JSDoc analogue that analyzes all accesses to the field and fails if it finds accesses from functions that aren't part of the struct that owns the field. You don't even need a comment on the field - you could copy Go's convention, add a comment to the struct definition marking it as "follows Go convention", and then fail any access from outside the struct to a field that starts with a lower-case character.
It doesn't prevent you from ignoring that tool and writing Zig code that imports the struct and accesses the field. It is, of course, not part of the Zig language itself. But if you adopted a tool like that, it would be your responsibility to run it across-the-board and pay attention to the results - same as how it is your responsibility to pay attention to the results if you added those JSDoc comments.
Exactly.
Every part of the language must support memory safety from first principles.
empirically untrue. several projects exist that bolt on extra safety to unsafe languages or unsafe parts of language. SeL4 for C, MIRI for rust unsafe. i guess ada/spark for ada too, is the OG, spark being added to ada 4 years after its first release
C# was already a very mature language when it had referenes and later "ref safety" added to it.
Swift, Linear Haskell, Chapel, Ada/SPARK are all counter examples from such claim.
Also OxCaml, from what I hear.
> It's impossible to add a borrow checker to any existing language.
Why do you say that. Have you tried and failed? It seems to be possible to add a borrow checker to zig, just as you can add MIRI to rust to get extra safety in unsafe blocks.
That's sort of what I'm doing...
I'm writing a language with Affine Ownership that transpiles to Zig and has a built-in FSM-based Green Fiber runtime.
Affine Ownership gives you memory safety + fearless concurrency + eliminates the need for Go's GC.
It's obviously going to slow down compilation - since you need to do Rust's borrow checking, etc. But I can do this incrementally as well...
> how about from the other direction, adding some kind of borrow checker to Zig? That sounds more within reach and practically achievable, possibly even in userland.
It's doable, and as static analysis. see sibling comment.
No, it would fundamentally change how Zig works.
no, it would not. If you do not believe me, you should try out the repo.
> if only somehow we could get Rust's safety with all of Zig's features
i periodically throw my unused codex tokens at this:
https://github.com/ityonemo/clr
One thing I wish Rust would improve over time is the builds. Its one of the biggest sources of wasted storage space on all my computers, builds a ton of libraries can take tens of gigs, it adds up very quickly. Not sure what the best solution is, one I found is to set the global build folder so dependencies get reused across projects, but imho it should be an OOTB default behavior whatever the real solution should be.
We are trading away disk space for faster builds. We could make them faster in some cases by using even more...
On the other hand, it would be good to garbage collect those caches. We are wrapping up work on a new layout for intermediate build artifacts that will make it easier to GC them.
Sounds like what I was thinking, that or for third party deps to go into the same temp folder, and anything not accessed in over a week, or so just gets auto wiped by rustc / cargo build process?
Can you talk a little more about that? How would that work, and what would the developer experience be like when using it?
I always got a kick out of that, coming from a JavaScript background where people constantly harp on the size of node modules.
My Tauri project, where the backend is much smaller code-wise than the frontend, has 9gb of rust artifacts (node_modules is 550mb for comparison)
Rust isn't great, and it shouldn't be a surprised since it's designed after npm. However one metric where nodes_modules is still worse for me is the sheer number of small files in it.
Having nearly one million files in nodes_modules isn't that unusual. The problem is that on most common file systems the minimum allocation is usually at least 4KB. So even if the actual data is less than 500MB, you end up with 4GB disk space used/wasted.
I wish ext4 had a feature to mark a file as "atomic" where it would allocate all atomic files in a long run, without room for expansion, and I suppose with very inefficient compaction upon deletion, but without any padding bytes.
A file “pointer” for byte exact files, pointer gets ditched for files that get updated or the pointer gets adjusted to another common file.
Quite interesting the hand waving of security issues with Zig, oh well.
If I want to use allocator debuggers I already have the production ready tools that exist for C and C++ for at least 30 years.
Compilers are not security sensitive, usually. And while UB could theoretically poison the generated code, this isn't a bigger risk than logic bugs.
> Compilers are not security sensitive, usually.
The compiler is one of the most significant trust boundaries we have. Its decisions can intentionally or unintentionally create vulnerabilities in programs compiled by the compiler, which means that if you can compromise a compiler you can compromise everything downstream.
Unsafe memory access in a compiler can be exploited in order to hijack the compiler itself (this is reported regularly in production compilers), allowing the attacker to then insert arbitrary code into compiled binaries. Not everything that a compiler absorbs from its environment is meant to be treated as source to be compiled, and in a memory unsafe compiler any of that input can silently turn into machine code in the compiled binary if an attacker is able to exploit the memory safety bug and hijack the compiler.
Of course they are, anything can be a gateway to inject backdoors, if security is not taken into account.
And as mentioned, if what Zig offers is already in Purify, there is hardly any added value over C and C++, without the headaches of a niche language.
Zig is a pre-1.0 language while Rust is post-1.0. This alone is settles which one to pick for may developers. The library support is probably favours Rust too. Rust build times are much slower than Zig, I get that, but I rarely optimize software for build times.
Zig is not pre-1.0 because it’s not ready for production (bugs or missing features), it’s pre-1.0 because they want to be able to make breaking language changes.
Nowadays when you can just point an agent at release notes and have it update everything, I actually prefer not having to wait through rare major releases to get new language features.
> Zig is not pre-1.0 because it’s not ready for production (bugs or missing features), it’s pre-1.0 because they want to be able to make breaking language changes.
This is a solved problem in other projects. Either use the version numbers as intended and bump the major version number on breaking changes, or use Rust-style editions to opt in to the newer versions of the changes.
Calling a project production-ready but keeping the version number below 1.0 and saying breaking changes are expected is a tired game. We've seen it backfire across a number of language projects like Elm, where the exact same claim was used to both encourage people to use it and then blame them when it backfired.
If it's production ready, go to 1.0 and then follow semver for breaking changes. I don't care if we get to Zig v73.2.0 as a result. At least we can see from a glance which versions need to be checked for breaking changes.
languages ideally should not have breaking changes ever.
on the other hand, a language with frequent breaking changes should not be considered production ready.
people are of course free to live on the edge, and if someone decided that zig is good enough and they are not bothered by breaking changes then they are free to use it for their production system, but that doesn't mean it's ready for everyone. so i prefer the zig approach.
> Nowadays when you can just point an agent at release notes and have it update everything
Except that means that not only you lose compiler bugfixes, you also pretty much has no access to the ecosystem. For most production codebases, this is a deal breaker.
> they want to be able to make breaking language changes
That sounds like it's not ready for production to me.
I invite you to read the release notes and see for yourself the types of breaking changes we’re talking about.
To me it is not much different from Lua, which despite being on 5.x for decades, makes breaking changes on minor releases (because it predates SemVer).
I also don’t see it being much different from any other language or language runtime that has a major release every year.
It’s fine to update at your own pace.
Nitpicking ahead:
I am not sure, but there might be a bug in their pattern matching example.
What happens if 'verb' is "GET" and 'path' is "/users/1234/posts/1234/extra_path/and/more/"? Will 'post_id' become "extra_path/and/more/"?
I tried running it in the sandbox, and it does indeed seem to buggily result in:
"Post ID: 1234/extra_path/and/more"
I suspect that the reason it is behaving like it is, is due to how it handles characters in the string literal. The example program exploits that only the slashes present in the string literal pattern are matched, to enable matching on 'page' having slashes. But then in the nested 'match', it forgot to account for any possible extra slashes.
Nitpicking end.
I have not read the whole post yet, but the pattern matching not requiring any allocations, seems very nice. The string literal patterns also seem interesting, though I am not completely sold on them, also as per the above possible bug. It seems really clean in some ways, but the specific semantics, I am not fully sure about. Maybe it is excellent, and is so clean and concise that it is overall less bug-prone than alternatives in other programming languages. I do not know.
The 35ms incremental rebuild is the part that sold me. I'd be curious to see the same benchmark on ARM once -fincremental gets there.
why not rewrite in ROC?? Would be much more cooler.
I think precious cognitive time should be spent more on the language itself rather than wasting it on rewrites.
The article links to https://www.roc-lang.org/faq#self-hosted-compiler to discuss this.
Didn’t know Roc was still being worked on. I think it’s an interesting concept for a language that I personally haven’t seen elsewhere
What made you think it was no longer being worked on?
Irrespective to the technical merits of both language, moving from a stable language to a pre-1.0 one that just lost his most popular open source project is a wild move.
> that just lost his most popular open source project
As they state in the article, they started the migration a year and a half ago, something that happened a few weeks back would never come into the decision making process.
is this uno reverse for bun post of zig to rust port ?
Can anybody explain to me why anthropic bought bun in the first place ?
Claude Code uses bun.
While I'm a rust enthusiast, I do agree that certain languages lend themselves well to particular domains. So a rewrite from Rust to something better suited is fine by me. In fact, while I do work on a rust project, I would not have and still would not recommend it as the choice for that particular project.
That being said, I had to do some double takes while reading this.
> https://rtfeldman.com/rust-to-zig#memory-safety-post-rewrite
I feel that it's a bit weird to compare a rather well tested 7 (?) year old rust implementation with a brand new not yet released less than a year old Zig implementation. Without that context, this looks like a bad comparison for rust, when it is in fact the complete opposite.
> https://rtfeldman.com/rust-to-zig#build-times
The swiftness of the Zig compilere here is insane, and would would very much shift my recommendation of Rust if it got to similar speeds.
That being said, I do find it funny that currently, the compilation speed is actually worse on Zig than Rust, despite Zig (anonymous commenters at least tbf) claiming the opposite for years.
How did you eventually discover the 35 ms figure for Roc? Did you have to temporarily update the codebase to 0.17?
> https://rtfeldman.com/rust-to-zig#memory-control-zero-parse-...
Nothing negative here. I did play around with implementing a scripting language in this DOD-ish, index-based paradigm and yeah, it is neat.
I was thinking that it might be possible to do resumable computation across the network like this (in the context of frontend frameworks "resuming" UIs), but ultimately I have no use for this so just the experience itself was enough.
One note here is that it does tend to break completely if non-pointer-free data is introduced. It seems like it's either all or nothing.
> https://rtfeldman.com/rust-to-zig#ecosystem-relevance
This is more of an LLVM thing, which is fair, but I find it funny that "LLVM unstable bad" while "Zig unstable whatever".
Overall though, this was an interesting read. And if the folks contributing to roc like zig then more power to them.
Last thing, the link here is broken (points to a TODO):
> Zig's compiler itself is another
> In fact, while I do work on a rust project, I would not have and still would not recommend it as the choice for that particular project.
wondering what type of project is that? I think besides some very embedded projects with very little memory where you need C/assembly, rust is good enough for all kind of projects..
I work both on a pretty much bog-standard web (GraphQL) backend and the frontend that uses it. We switched over from Apollo on node to async-graphql on Rust.
The runtime performance is much better, but the compiler time performance is terrible. To be fair, this is mostly the fault of async-graphql, but that doesn't really matter all that much. For example, it's not uncommon for a single character SQL query change to trigger over a minute long incremental rebuild.
The rust compiler is just choking on the number of generics and codegenned functions.
I've personally looked at how to improve this, but short of breaking up the type graph using federation, nothing can help. Not even cranelift makes a noticeable dent.
Additionally, the team started off composed by a bunch of TypeScript/React/Node developers, so mistakes were made along the way.
Honestly, I would have recommended to just use C#.
That's not to say that I don't think Rust can work for web development. We have some (GraphQL-less) services where Rust is a great fit. Just maybe shouldn't have been the default. That or give up graphql ...
For whatever it's worth, I share some of your async-graphql woes, though I haven't investigated things deeply enough to have strong opinions about what to do instead.
I think there will be soon a wave of rewriting rust to language X coming up.
The other way around.
Rust is also one of the best languages to use with AI.
I don't even know what Zig is but I've seen this topic come up so many times on this site that I'm starting to think the people who are actually doing this are unsure themselves whether it's a good idea or not.
Basically the security model of Modula-2 or Object Pascal, with a curly brackets syntax, and compile time execution.
Some folks embrace it as some kind of novelty.