337 points · by jacobwg · 4y ago · 177 comments
/me runs
This may not be as nice as the compiler yelling at me even before the program is run, but it certainly makes for a much simpler language.
I've had this code yesterday on an embedded arm cortex m0:
bool tx_byte(char msg) { for (int i = 0; i < 8; i++) { tx_bit((msg >> i) & 1); } }
This function wouldn't return. What's even stranger, the variable i would increment past 7. The for-loop just continues.
I got a warning about the missing return statement in that function, but didn't think there could be a connection to my bug. It turned out that adding that return after the for loop fixed it.
The warning was one among about 100 others, as I was refactoring quite some code at the time. I only started working on the warnings after I had decided that me an two of my colleagues were just overlooking something and would fix the bug another day.
All that I wanted to say is that, no, C doesn't make you aware of what is happening. It has this giant pit of UB that does weird things when you fall into it. I was lucky that in my instance, I got a warning. I know other UB just works most of the time and goes unwarned.
Wouldn't that even be a compiler bug allowing no return statements, but then incorrectly handling scope?
This is the whole story, really.
https://stackoverflow.com/questions/7280877/why-and-how-does...
With a enough printfs() I was able to whittle the problem down to: A local variable "b" was changing after some function call that looked like: "call(&a)". Turns out because our program looked like "{ int a[3]; int b; ... call(&a); }" an off by one error accessing "a[4]" in the function was overwriting variables never passed to it!
Felt like the champ figuring out. (This is a 15 year old story from freshman year, so I hope I got the details right.)
But still: If you passed the array and referenced it wrong it would change local variables in some remote stack frame.
Not necessarily. Many C programming errors invoke Undefined Behaviour, and then "appearing to work correctly" is a permissible option. So you will miss the programming error, until a change seemingly unrelated to that part of the system will trigger some segfaults or wrong results, or allow a determined attacker to use your program to launch calc.exe.
Unfortunately it isn’t true, C let’s you write plenty of broken programs that don't fail at run time, despite making a complete dogs breakfast of your systems memory space, instead we get crap like Heartbleed instead.
var ch chan bool
for i := 0; i < 10; i++ {
go func() {
// do something amazing
ch<-true
}()
}
Oops, I just leaked 10 goroutines, because I forgot to `make` the channel instead of declaring it, so its nil and will block indefinitely. Unless the program encounters an complete deadlock of all gorutines, this will not crash anything, and the caller of this code has no way of knowing it happened.Broken code can be written in any language, no matter how much checks & convenience it offers.
Sure, valgrind exists, but that is not native execution.
I assert it’s possible to have a simple language where it’s difficult to shoot yourself in the foot. C just happens to be a simple language where it’s exceedingly easy to shoot yourself in the foot.
Zig would be one such example.
Anyway it’s simultaneously a very simplified cousin of Haskell (similar syntax but most of the advanced syntactic and type stuff dropped), and where the current movement to make compiler error message more readable, conversational, and helpful (e.g. decoration, explaining the “reasoning”, providing possible solutions) originates.
Those who aren't careful enough to free up allocated memory are the same types of people who leak memory in Java.
You can't fix lack of knowledge with a compiler. You can only catch accidental mistakes, but that assumes that the norm is for the person to know what they are doing and a lot of people have only superficial knowledge of the tools they are using.
We already have accident catching tools for C. What C doesn't have is a helmet, training wheels and padded walls, which is by design.
That isn't true at all. The majority of my and other's bugs I hit working with C (I did C for several years at a large company) were because they explicitly did not fail when people forgot things. If you iteratively learn C you learn tons of bad behaviors as C does not tell you when things are broken.
It's worth looking at deadlock detection at compile time today. Not just to prevent bugs. Sometimes, on some CPUs, the compiler could potentially turn some mutexes into fence operations and become "lock free".
In Rust, code tends to do a lot of scope-based locking. There's a lot of
item.lock().unwrap().dosomething()
Now, if the compiler detects that 1) every lock on item is scoped, and 2) everything done inside the lock is short and non-blocking, then that lock could potentially be optimized into fence instructions. Worth thinking about.There's an analogous case for RefCell items. RefCell is a lot like Mutex, except that you call "borrow" instead of "lock", and if the item is ever "busy", waiting won't help, because your own thread made it busy. If every use is a scoped borrow and there are no inner borrows of the same object within the scope of the outer borrow, that's the good case. Reference counts aren't needed at all.
I think that somewhere in this space lies the solution to the back-reference problem, but I haven't gotten there yet.
Deadlocking Go-style synchronous channels isn't hard. In practice they're practical to use because they're not particularly hard to not deadlock, either, but I can certainly deadlock them in code if I tried. But I'd be using patterns I'd normally be suspicious of.
(By contrast, conventional mutexes are hard to use without deadlocking, because as soon as you have more than one you have troubles. I use mutexes a lot in Go, but my rule is never take more than one at a time. As soon as you are tempted, do something else. IMHO, the conclusion from the 1990s and early 2000s is wrong... it is not that multithreading in general is impossibly hard, it is that multithreading with multiple mutexes is impossibly hard. If you stay away from that, rather than "impossibly hard" it is merely a challenge, but one humans can rise to meet. I think there's an unjustified residual fear of multithreading to this day that stems from this misunderstanding. And I mean "threads" just as multiple independent simultaneous execution, without regard to any particular technology used to implement them.)
That language will need to be built around this limited set of programs though, and is really unlikely to be retrofitted in Rust, like C++ can't realistically add a borrow checker at this point.
Probably not. This would have to be extremely limited and restrictive in order to avoid false positives (which would be outright miscompilations). The more restrictive an optimisation is, the less valuable it is, and the lower the ROI.
This would be an unlikely-to-achieve-anything optimisation around atomics, which compilers already don’t bother much with because they’re hard to get right and have a low ROI.
I don’t think it’s true because if you don’t “hold” the mutex there’s no guarantee that the mutex-protected data is consistent, unless it’s atomic at which point you’re probably better off optimising to an atomic read. Which compilers are unlikely to bother with either way, because optimising atomic operations would be both risky and low-return.
I thought the same. Memory fences alone can't guarantee mutual exclusion.
struct FooInter {
actual_data: HashMap<...>,
}
impl FooInner {
fn do_something(&mut self) { ... }
}
pub struct Foo(RwLock<FooInner>);
impl Foo {
pub fn do_something(&self) {
self.0.write().do_something();
}
}
The rule is that FooInner doesn't know about the lock (so calling other methods is safe), while Foo methods can't call other Foo methods (so you can't lock anything twice). You can even move Foo and FooInner to different modules to hide FooInner's contents from Foo, though I rarely find that necessary.I know this is subjective, but for me, this works better than what the blog post suggests -- at least, I haven't gotten it wrong by accident yet.
I can recommend the ambassador crate to go with this pattern -- it can be very useful for avoiding boilerplate for the newtype struct.
Really the hardest part is naming... I've also settled on FooInner, but I'm still not entirely happy with that convention.
Any serious Go programmer ought to have golangci-lint or equivalent running somewhere. I prefer pre-commit, but CI/CD will do too.
An advantage of golangci-lint is that is not in the core compiler, so you can get some really opinionated linters from the community, some of which you're going to love and some of which you're going to hate, or linters written really quickly and hammered out in the real world rather than waiting for the full release cycle.
A disadvantage of golangci-lint is that it's not in the core compiler, so you have to actually fetch it yourself, maintain it (configure it), etc.
With golangci-lint, Go is still not Rust, of course, but it gets it a pretty decent way towards being a serious, quality language. Most languages need some augmenting to be serious, quality languages, because it isn't generally appropriate to put all the requirements for code into the compiler, for many reasons. Rust is somewhat exceptional in how much they've put in their compiler. Things like C and C++ need immense, high-quality support from static analyzers to be even remotely safe to use on a network. (So, yes, I don't consider C or C++ "serious, quality" languages in the absence of that static support. I don't even consider it close, honestly. I don't consider very many languages to be serious, quality languages out of the box.)
And what's really nice about clippy is that it re-uses a lot of the compiler's infrastructure instead of having to duplicate it, so it has the same high-quality error messages, and stays in sync with rust's new language features.
[0]: https://rust-lang.github.io/rust-clippy/master/index.html
Now, I will fully grant you, I enjoy Rust and like programming in it for fun, but have not kept up on what projects have been made in the wild and professional worlds with it, past Mozilla, TBH. I know a lot of companies are recruiting, but haven't seen much coalesce. Could be my ignorance, though.
At work I use both C++ and go. My experience working on a C++ project is that it takes several minutes just to build, so when I make a change and try to run the unit tests, I find myself wasting a lot of time. I'll often get bored and go on HN for example :)
When working on go it's like night and day. Projects mostly compile in less than 30 seconds (unless it has a lot of C++ dependencies). With this pattern I can maintain my focus and continue the modify-build-test loop, I find I end up being a lot more productive.
You might want to adjust your workflow and make it fit the language better. Avoid relying on unit tests for semantics that can be trivially checked by the type system. Get into the habit of launching builds as part of your work, then check back on the test results after they're done. A build doesn't have to "interrupt" your flow if you plan it correctly.
I have worked in Pascal(Delphi), that is a bit more useful in catch issues at comptime.
Being able to iterate quickly is also a way to fix errors without loose the train of thought!
--
And answering your question: Slow comptimes are directly proportional to burn more energy (no green, cost more). And it impact the cost of that CI pipelines and all that.
And yes: I have been hit by slow build times with Rust with serious bugs/problems with customers, unable to move fast enough.
One of the worst affect me with a combination of several issues that get slow to note because each one was slow to compile-ship-see effects, enough bad to almost lose a few customers...
So, in my mind, the #1 thing I wish Rust has, more than anything, is speed!
- downloading a Rust compiler;
- downloading/compiling `rustfmt` including dependencies;
- downloading/compiling `mx-tester` (the Rust-bassed tool we use for testing) including dependencies;
- downloading/compiling the actual project including dependencies.
This could be 8-10 minutes wait every time I push code to CI. This also means that debugging CI itself takes days.
Admittedly, caching can help a lot. I just haven't configured it yet.
The first example: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMO...
Unreachable code detected
Along with some typos since `i` isn't declared. fn add() { ... }: mispleading name or incorrect implementation `a - b`
You know, once upon a time I would have thought that was categorically impossible, but now, you know, it actually seems like something that might not be that far off.> It's just not something Rust is designed to protect against - at least, not today.
...maybe, one day. :)
Advice like this is frustratingly non-general: you might be doing addition over GF2[1] in which case `fn add(a, b) { a ^ b }` is a perfectly sound function. I've worked on a codebase, in Rust, where that's the case[2]!
[1]: https://en.wikipedia.org/wiki/Finite_field_arithmetic#Effect...
[2]: https://github.com/trailofbits/reverie/blob/master/src/algeb...
This, incidentally, also helps fellow humans reading the code who'll see that it's all intentional and won't flip with "wtf why does it XOR in an add method?" even if just for a second.
As an example, those linters that have a message for each programing style and a rule to convert between them are stupid. They might be useful as some other kind of code, but as linters they are not just useless, they are actively harmful.
Then the function name, class, and/or comments should be making that clear! In this case, the BatchGF2 class does so. Maybe somewhere else a Fourier class has `fn add() { a * b } // a and b are in time domain`
but a standalone add() function with no comments or class should probably not be doing a ^ b, a - b, or a * b.
some github copilot like linter can then draw from other GF2, Fourier, etc code references vs vanilla add functions
Btw, have a look at hlint. It sometimes gives rather involved hints about how you can restructure your code.
I suppose the parking_lot implementation elides some checks for the sake of performance.
EDIT: It seems it can happen with the standard library's RwLock too[1]. Perhaps it's a Linux peculiarity?
Pretty sure the spec is entirely silent on the subject.
> Essentially, a pending write lock should block new read locks from being acquired -- this is a feature, if it didn't do that
That is an implementation detail of the lock. I don’t think either POSIX specifies the bias of its rwlock, and Rust explicitly documents that it does not and delegates to the OS.
Plenty of RWLock will, in fact, starve writers under heavy contention (both read-bias and write-bias have their pros and cons).
I would not call it a “linux peculiarity” as any system could have any priority policy and could change it unless explicitly guaranteed, which this rarely is.
> It's a pretty radical design choice, to force you to be aware that, yeah, since you're creating a new value (out of the two parameters), you will have to allocate. And so it forces you to allocate outside of the Add operation itself.
Forcing you to think about allocation is good for many situations.
Making you do an extra allocation is a bad way to do that. And the only way I can think of to avoid that would give up having the function be generic.
Which would mean using String::with_capacity based on both &str.
Not making a string from one side, then very likely resizing it to add the other. The generic code+call will often make two allocations.
Sure, if you want to optimize that, then create your "foo" string with the extra capacity instead of doing `"foo".to_string()`, eg `{ let foo = String::with_capacity("foo".len() + "bar".len()); foo.push_str("foo"); foo }`. It has nothing to do with the generic `add` function; it can stay generic as it is just fine. Even a function specialized for adding String and &str could not go back in time and change how much capacity the String was created with.
Edit (1h later): It's also worth noting that:
- This desire of `Add::add(&str, &str) -> String` only seems to come up with people learning the language and bringing expectations from other languages. I've never seen production code that would've benefitted from it.
- As much as the ship has sailed with libstd functions hiding allocations via the global allocator where you may not expect them, the less new cases get added the better. So I'd rather not have `impl Add<&'_ str> for &'_ str { type Output = String; }` added to libstd.
- If you really do have two str literals that you want to concatenate, just use `concat!()`. Not only does it work, but also it works at compile-time and without any allocation (it evaluates to a `&'static str`).
func add(a interface{}, b interface{}) interface{} {
if a, ok := a.(int); ok {
if b, ok := b.(int); ok {
return a + b
}
}
if a, ok := a.(string); ok {
if b, ok := b.(string); ok {
return a + b
}
}
panic("incompatible types")
}I mean I know there's better examples out there, but in practice I've not missed a lack of generics in Go yet. Mind you, I'm not writing libraries for e.g. json parsing.
Actually there is one place in my application where I use interface{}, it's a bit of code that converts values to XML strings, but it needs different logic for different types. I don't think generics will solve that: https://go.dev/play/p/TtwyNZ7oOPx
Before we move on, I'd like to congratulate you on reading this far. Believe it or not, you're in the minority!
The title is very misleading when the content is a very, very general discussion of compile-time versus runtime errors, mostly focusing on problems that Go doesn't catch at compile time.
TL;DR: the mistake Rust doesn't catch is recursive mutex locks.
It does seem like it would be good to catch that one, and that the borrow checker in some form ought to be able to do it -- it should be able to track the static scope of a mutex lock, and block further attempts to lock it inside that scope.
Most articles don't do that, and so they're "short and to the point", but only to a tiny audience that already has the same shared culture. There's always readers complaining that they knew half of it and so I "wasted their time", but they forget about the other half, and also other readers.
Ideally, to please everyone, I would have to write a tailored article /just for them/, filling just the gaps they have. I do that on occasion, but I charge a lot of money for it :)
It is through this journey that we can appreciate how good the Rust compiler is in many cases, but also its limitations (recursive mutex locks).