What are your favorite statically typed, compiled, memory safe programming languages?

CoderSupreme@programming.dev to Programming@programming.dev – 105 points –
120

With no context, this could be an honest attempt to learn about different tools, a thinly veiled set-up to promote a specific language, or an attempt to stir up drama. I can't tell which.

It's curious how such specific conditions are embedded into the question with no explanation of why, yet "memory safe" is included among them without specifying what kind of memory safety.

Yeah, arguably the only answer to this question is Rust.

Java/C#/etc. are not fully compiled (you do have a compilation step, but then also an interpretation step). And while Java/C#/etc. are memory-safe in a single-threaded context, they're not in a multi-threaded context.

C# has native compilation capability, thanks to Native AOT

https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/

I mean, yeah, valid point. JVM languages also have GraalVM for that purpose.

But I'm playing devil's advocate here. 🙃

Arguably these don't count, because they're not the normal way of using these languages. Reflection isn't properly supported in them, for example, so you may not be able to use certain libraries that you'd normally use.

These also still require a minimal runtime that's baked into the binary, to handle garbage collection and such.
Personally, I enjoy fully compiled languages, because they generally don't lock you into an ecosystem, i.e. you can use them to create a library which can be called from virtually any programming language, via the C ABI.
You cannot do that with a language that requires a (baked-in) runtime to run.

But yeah, obviously someone just specifying "compiled" probably won't have all these expectations...

Arguably modern c++ ( aka if you don't use raw pointers), fits all categories.

I don't know much about C++, but how would that do memory safety in a multi-threaded context? In Rust, that's one of the things resolved by ownership/borrowing...

Or are you saying arguably, as in you could argue the definition of the categories to be less strict, allowing C++ as well as Java/C#/etc. to match it?

Because you would be using std::shared_ptr<> rather than a raw pointer, which will automatically deallocate the memory when a shared point leaves the scope in the last place that it's used in. Along with std::atmoic implements static functions that can let you acquire locks and behave like having a mutex.

Now this isn't enforced at the compiler level, mostly due to backwards compatibility reasons, but if you're writing modern c++ properly you wouldn't run into memory safety issues. If you consider that stretching the definition then I guess I am.

Granted rust does a much better job of enforcing these things as it's unburdened by decades of history and backwards compatibility.

Modern C++ does use references, which can also reference memory that is no longer available. Avoiding raw pointers isn’t enough to be memory safe.

How are they not memory safe in a multi-threadded context?

There's nothing to prevent data races. I myself have fallen into the trap of using the same list from multiple threads.

I don't think data races are generally considered a memory safety issue. And a lot of languages do not do much to prevent them but are still widely considered memory safe.

Even though they are not what people mean when they say "memory-safe", it is technically a kind of memory safety. It is unsafe to modify non-mutexed/non-atomic memory that another thread might be modifying at the same time.

Yeah, that is why I prefixed that whole comment with "arguably".

I feel like the definition of memory safety is currently evolving, because I do think data races should be considered a memory safety issue.
You've got a portion of memory and access to it can be done wrongly, if the programmer isn't careful. That's what memory safety is supposed to prevent.

Rust prevents that by blocking you from passing a pointer for the same section of memory into different threads, unless you use a mutex or similar.
And because Rust sets a new safety standard, I feel like we'll not refer to Java and such as "memory-safe" in twenty years, much like you wouldn't call a car from the 90s particularly safe, even though it was at the time.

There's a reason why data races aren't considered a memory safety issue, because we have a concept that deals with concurrency issues - thread safety.

Also for all it's faults, thread and memory safety in java aren't issues. In fact java's concurrent data structures are unmatched in any other programming language. You can use the regular data structures in java and run into issues with concurrency but you can also use unsafe in rust so it's a bit of a moot point.

Oof, I guess, you're not wrong that we've defined data races to be the separate issue of thread safety, but I am really not a fan of that separation.

IMHO you cannot cleanly solve thread safety without also extending that solution to the memory safety side.
Having only one accessor for a portion of memory should just be the n=1 case of having n accessors. It should not be the other way around, i.e. that multiple accessors are the special case. That just leads you to building two different solutions, and to thread safety being opt-in.

That's also the major issue I have with Java's solution.
If you know what you're doing, then it's no problem. But if you've got a junior hacking away, or you're not paying enough attention, or you just don't realize that a function call will take your parameter across thread boundaries, then you're fucked.
Well, unless you make everything immutable and always clone it, which is what we generally end up doing.

You can use the regular data structures in java and run into issues with concurrency but you can also use unsafe in rust so it’s a bit of a moot point.

In Java it isn’t always clear when something crosses a thread boundary and when it doesn’t. In Rust, it is very explicit when you’re opting into using unsafe, so I think that’s a very clear distinction.

Java provides classes for thread safe programming, but the language isn’t thread safe. Just like C++ provides containers for improved memory safety, and yet the language isn’t memory safe.

The distinction lies between what’s available in the standard library, and what the language enforces.

Swift fits the description too

Most people would consider it so, but it actually does not either fulfill the argument I posed there: https://forums.swift.org/t/what-language-is-more-memory-safe-swift-or-rust/31987

Swift does have data race safety as of Swift 6 with their actor-based concurrency model and are introducing noncopyable types/a more sophisticated ownership model over the next few releases

Hmm, that sounds quite interesting. But because I've had to rebut that for everyone else that responded: Is it opt-in?

I guess, I would be fine with opt-in for the actor pattern, since you either do actors in your whole codebase or you don't, but otherwise, opt-in often defeats the point of safety measures...

It's opt-in in Swift 5 mode and opt-out in Swift 6 mode, the Swift 6 compiler supports both modes though and lets you migrate a codebase on a module-by-module basis.

Agree that opt-in sort of defeats the point, but in practice it's a sort of unavoidable compromise (and similar to unsafe Rust there will always be escape hatches)

The question mine as well be "what is your favorite compiled language?". There is a lot of overlap between the possible answers.

Yeah, I like subleq.

  • compiler is extremely fast, faster even than tinycc
  • strongly statically typed: all values are ints. Since it's all of them, you don't even need to write it!
  • memory safe: the entire (virtual) address space is guaranteed to be accessible at all times so there's no way to leak any of it (can't release it anyway) or to segfault (it's all accessible).

Subleq is the obvious winner in my mind.

Rust for now, by a wide margin. But I'm following other languages that I think have the potential to surpass it, including Vale (promises way more than it delivers currently), Koka, Hylo, maybe Lobster.

Honest question, what would make you pick Gleam over Elixir? Both seem to have significant overlap

I dunno it looks well designed but I dunno why I would use it instead of Rust.

That is a very specific subset

Garbage collection is still allowed, and technically JIT languages are still compiled so it really isn't that restrictive

Not that specific tbh, most newer native languages these days are compiled and memory safe (Rust, Swift, Go, Kotlin Native, etc)

As others have said, Haskell and Rust are pretty great. A language that hasn’t been mentioned that I REALLY want to catch on, though, is Unison.

Honorable mention to my main driver lately: Purescript

Tell us more about unison

Hard to describe in one phrase other than to say:

NixOS is to Linux as Unison is to Haskell

Content-addressing used in the context of programming languages in the service of solving the problem of distributed systems and their inability to share code across time and space.

Haskell has a content-addressed module that was perhaps influenced by Unison.

Here’s an excellent interview with one of the authors of Unison:

https://youtu.be/zHzpoVgqgc4

C# is good too. If you havent heard of lobster you should look into it.

C# isn't exactly compiled, at least not into machine language. It is transpiled into byte code that is run on a virtual machine that on turn is an interpreter/JIT-compiler.

Depending on why someone is asking for a compiled language that may or may not be a problem, because to the one writing the code it looks like a compiled language, but to the one running it it looks like an interpreted one.

Not necessarily these days! With NativeAOT, C# can be compiled to machine code.

It is compiled to bye code. Just to be clear transpiling is completely different. It is also not interpreted.

But ahead of time compilation is available now. So you can compile straight machine code.

The newer tiered JIT can actually give better performance than a traditional compiler as well.

Overall C# is an awesome language. If performance is absolutely critical you can use raw pointers and manual memory management, but obviously you lose safety then.

It is compiled into bytecode. A transpiler translates to another programming language with the same level of abstraction. A compiler translates into a level that is nearer to or machine code.

Ada, hands down. Every time I go to learn Rust I'm disappointed by the lack of safety. I get that it's miles ahead of C++, but that's not much. I get that it strikes a much better balance than Ada (it's not too hard to get it to compile) but it still leaves a lot to be desired in terms of safe interfacing. Plus it's memory model is more complicated than it needs to be (though Ada's secondary stack takes some getting used to).

I wonder if any other Ada devs have experience with rust and can make a better comparison?

I have done quite a bit of C, C++, Ada, and Pascal development. I recently got into Rust. I am still getting used to Rust, but it feels a bit like someone tried to apply Ada to C++. I like the modern development environment, but I am slower writing code than I would be in Ada or C++. The one feature of Ada that I really like and want other languages to adopt is the Rep spec. I write driver code and being able to easily and explicitly identify which symbol corresponds to which bit is really good.

I would use Ada or Spark in a heartbeat if there was an easy-to-use, mature cross-platform GUI library for it.

OCaml.

Sad I had to scroll to the end to see this.

Ocaml is brilliant and has the nicest type features. It's almost like Haskell but more approachable imo.

I’ve recently been trying to learn OCaml and find it really nice. The major pain points are

  • C-style separate compilation with manually created headers
  • Small standard library
  • No generic print function
  • Hard to use external libraries

Is Printf.printf not a good generic print function? It's even variadic!

When you want to print something, you can’t just Printf.printf x, you have to explicitly give it instructions on how to print a value of that specific type.

Coming from Haskell, OCaml always felt a bit strange to me. The double semicolons, the inconsistency in the standard library between curried and uncurried functions etc. Maybe I'm confusing it with Standard ML though, can't remember.

I know double semicolons are a thing, but I've never had to use them. I forget what they're for, but yeah it's supposed to be an escape hatch for something that shouldn't be happening iirc.

The curried snd uncurried functions... Maybe you are confusing with SML, because everything in ocaml is curried by default. Though admittedly the standard library could be more complete, but I personally am happy to use third party dependencies for less common things.

As a Haskell programmer, "OCaml has the nicest type features" hurts just a little bit.

I sometimes teach a course in OCaml. The students who are very engaged inevitably ask me about Haskell, I encourage them to try it, and then they spend the rest of the semester wondering why the course is taught in OCaml. Bizarre how different that is from when colleagues in industry want to try Haskell.

Largely reasonable?

Haskell is not good for systems programming which sums up about 60-70% of that post. Laziness is lovely in theory but many industry uses of Haskell use stricthaskell for all or most of their code, so I certainly agree with that part too.

Their largest complaint about using Haskell for small non-systems programs seems to be the mental overhead induced by laziness. But for me, for small programs where performance isn't a huge concern (think Advent of code or a script for daily life) laziness reduces my mental overhead. I think that author is just especially concerned about having a deep understanding of their programs' performance because of their systems background. I worry about performance when it becomes relevant. Debugging Haskell performance issues is certainly harder than strict languages but still totally doable.

The lack of type classes or other form of ergonomic overloading in OCaml is easily the single "feature" most responsible for the language never taking off.

As someone who is not deep into type theory or functional programming, can you please explain why you mean by "ergonomic overloading"?

My understanding is that ocaml mitigates the need for type classes through its more advanced module system. So far I have been enjoying the use of OCaml modules, so I'm curious what exactly I'm missing out on, if any.

Thanks for taking the time to talk with me btw!

You have to be explicit about which module you're using at all times, even though 99% of the time only one could apply. When the type class resolution is unique, but complicated, there's no mental overhead for the Haskell programmer but getting all the right modules is a lot of overhead for the OCaml programmer. It also lets us write functions that are polymorphic under a class constraint. In OCaml you have to explicitly take a module argument to do this. If you want to start composing such functions, it gets tedious extremely fast.

And then even once you're using a module, you can't overload a function name. See: + vs +.. Basically modules and type classes solve different problems. You can do some things with modules that you cannot ergonomically do with type classes, for example. create a bit-set representation of sets of integers, and a balanced search tree for sets of other types, and expose that interface uniformly from the same module functor. But Haskell has other ways to achieve that same functionality and more.

OCaml's type system cannot replicate the things you can do with Haskell's higher kinded types, type families, or data kinds at all (except for a fraction of Haskell's GADTs).

I started learning Go about 3 months ago and it quickly became one of my favorite languages. It feels like C with a bunch of Python niceties thrown in. And performance isn't super critical in my work so being garbage collected is fine with me.

People don't understand that JIT languages are still compiled, JIT literally describes when it's compiled.

That said, F# and/or OCaml.

Scala 3 native. If the compiler was faster I'd be even happier. Curious to try Ada

Nim. Small compiler, small executables, easy to understand (except the macros, I still can't get my head around them).

FreePascal. Yeah yeah, Pascal's dead, etc etc, but it being so verbose and strict certainly help programmers (or at least me) keeping things somewhat tidy.

Also shoutout to V

After months of no practice, I forget quite a lot of stuff about them, regardless of language; therefore, none

EDIT: None of them is memory safe, that is

You forgot that beauty - "undefined behavior"!

Memory-safety can guarantee only so much safety! C++ can still blow up in your face, even with all the alleged memory-safety built into C++, thanks to all the UB traps in C and C++.

Rust is the closest language that has no such "gotchas".

Crystal, but only because I’m a full time Ruby on Rails (and sometimes Hanami!) programmer.

It’s fantastic, and I had an excuse to use it at work when we needed to gather PHP Watchdog logs from a MySQL database and format, output them to STDOUT in a Kubernetes environment. (This was necessary for our log monitoring tools expecting data in a standard way, AKA not connecting to a database. 🤦‍♂️)

I know there are perhaps better options out there (Go, Rust, etc.) but from a Rubyist’s point of view Crystal gives you that “flow” from working in a beautiful language but with the performance boost of compiled software.

I'm anxiously waiting for Crystal to be able to compile for Windows so game development with it can get a kickstart

I’m kind of sad to say that I don’t think it’s going to reach the adoption level of Ruby but I hope I’m wrong.

C++ with -Wall -Werror, and no pointer diddling.

Its definitely best to try and avoid raw pointers, but even if you try really hard I found it's not really possible to get a Rust-like experience with no UB.

Even something as simple as std::optional - you can easily forget to check it has a value and then boom, UB.

The C++ committee still have the attitude that programmers are capable of avoiding UB if they simply document it, and therefore they can omit all sanity checks. std::optional could easily have thrown an exception rather than UB but they think programmers are perfect and will never make that mistake. There are similar wild decisions with more recent features like coroutines.

They somehow haven't even learnt the very old lesson "safe by default".

If I wanted memory unsafety I think I would consider Zig instead of C++ at this point.

I recently got bitten by exactly that std::optional UB and here I was thinking 🤔 after 12+ years in the industry starting all the way back in the day with C++03 that modern C++ was supposed to make things better.😐

purescript if you count “compile to js” as compiled.

Otherwise Haskell

That's transpiling, not compiling. Compiling is usually meant as "directly to machine code", but I am yet to find an "official definition".

There is no official definition, in part because there isn't any formal way to define the term that satisfies our intuition.

Most treatments will handle "transpiling" as a special case of "compiling" and some will even handle decompilation as a special case where the object language is higher level than the source. Of course, even defining "higher level" can be quite hard.

Plenty of languages "compile to C" and I see no issue with saying something "compiles to js," especially given that js mostly lacks features of purescript rather than the other way around.

transpiling is just a type of compiling. compiling in no terms means 'directly to machine code'.

Scala is the the first I used and I like it a lot. If I had more time I'd love to give ocaml a decent try but I don't think I can get into it these days.

Elm, which is the loveliest language ever.

But I'm not sure if compiles to javascript counts as compiled, in which case haskell, which is considerably less lovely but still good.

Roc isn't finished, but it might turn out lovely, I don't know.

C++, with some Skill

/s

but seriously, I don't know any language with a good, C/Cpp-like Syntax (so not Rust), with a good compiler (again not Rust). So I'm sticking to Cpp.

You should check out zig, its compiler can even be used for c/c++. If you have time to listen to an interview, this developer voices interview on zig explains some of the advantages of this: https://www.youtube.com/watch?v=5_oqWE9otaE&amp;t=3970s

Thinking about zig for some stuff.

Mostly because those rusticles are pissing me off.

I don't know what you are talking about?

Rust is such an amazing language, it's so safe and clean and beautiful and simple and clear to read and such wow community that are making amazing crates for cargo because cargo is so cool I like it so much so easy to....

Oh, and your fav lang sux alot!1 lolololllll

"Hey Linus, why haven't you rewritten the kernel in rust yet, you idiot?!?! Don't you realize you're missing the future, old man!?!?"

What's so bad about the Rust compiler? I know it's slow, but given all the analysis it's doing, it makes sense. And, from my own experience, setting correct optimization levels for dependencies along with a good linker makes incremental builds plenty fast.

Julia

I wouldn't consider Julia statically-typed; am I wrong?

It's actually optionally-typed. But if you're liberal with type annotations you can treat it as statically typed.

Python

They specified statically typed languages. Python would be dynamically typed

Python is dynamically typed by default, but lots of Python is statically typed.

No python is statically typed. You have type hints, which makes the language tolerable but like their name implies it's a hint at the type. You can perfectly legally pass in something completely different that doesn't conform whatsoever.

The primary thing static languages provide is static typing, that being the ability to determine before runtime that all the types are valid. A good example of this is how C++ programs will refuse to compile if you try to invoke a method that doesn't exist on the type. That's because it's statically typed. At compile time you know that the code is wrong. Dynamic languages fundamentally don't work like that. You cannot know until runtime if the method you called or the field you are trying to touch exists or not. Again type hints help a lot with this but that doesn't change how the language actually operates.

All static typing means is that types don't change, eg you can't declare a var as a string and later assign a number to it.

No.

Name one statically typed language that doesn't have that property. Name one non statically typed language that has that property.

It's much more involved than that. For example, static type systems involve checking that the functions you call accept the types of parameters you're supplying then. It's a necessary part of static typing but alone is not sufficient.

If this code were a valid program in some hypothetical language but only failed at runtime then that would be an example of dynamic typing because the types cannot be verified statically (e.g., at compile time).

var a = 1
a = "a"

But you're right, I don't really know of any languages like that. I could've sworn I heard this called strong typing but I can't easily find a source. And strong/weak typing are a mess of definitions nobody agrees on.

1 more...
1 more...
1 more...
1 more...
1 more...
1 more...
1 more...
1 more...

C is memory safe if you program it well enough, so I guess C

every single language (except Vlang of course) is memory safe if you program it perfectly.

Very, very few humans are capable of doing that, especially with C.

Every car has airbags if you drive well enough. Right?

You can still make stupid mistakes in Rust. It may make it harder to make the most common mistakes, but pretending the guardrails are prevent any type of mistake is asking for a problem to happen.

The only one pretending mistakes can't happen is the person I replied to. Mistakes definitely can happen and no programming language is fool proof.

Continuing my car analogy, would you rather drive a car with airbags and seatbelts or one without them? Of course you can still have a fatal accident, but it's nice to have safety features that make it as unlikely as possible.

3 more...