by angrygoat · 6y ago · 0 comments
I spent a few years as a scientific programmer and this is exactly the sort of thing that just bites you on the behind in C/C++/Fortran: the undefined behaviour can actually manifest as noise in your output, or just really hard to track down, intermittent problems. A big win to get rid of it.
The overflow-is-a-bug-saturating as would be the default, and there would be a separate sat_as for "I know this saturates, it isn't a bug.". ::sigh:: Rust went through this same debate for integers, initially rejecting the argument I'm giving here but switching back to it after silently-defined-integer-overflow concealed severe memory unsafty bugs in the standard library.
Well-defining something like saturation actually reduces the power of static and dynamic program analysis because it can no longer tell if the overflow was a programmer-intended use of saturation or a bug.
Having it undefined was better from a tools perspective, even if worse at runtime, because if a tool could prove that overflow would happen (statically) or that it does happen (dynamically) that would always be a bug, and always be worth bringing to the user's attention.
So now you still get "noise" in your output, but it's the harder to detect noise of consistent saturation, and you've lost the ability to have instrumentation that tells you that you have a flaw in your code.
So I think this is again an example of rust making a decision that hurts program correctness.
> So I think this is again an example of rust making a decision that hurts program correctness.
Could you expand on other examples?
Rust has a linter called Clippy which absolutely does call out things like that. It can do so because there are other mechanisms in the language which provide the same functionality without ambiguity. I believe casting with `as` is linted against by Clippy.
[1]: https://doc.rust-lang.org/nomicon/what-unsafe-does.html
[2]: https://nora.codes/post/what-is-rusts-unsafe/
[3]: https://play.rust-lang.org/?version=nightly&mode=debug&editi...
[4]: https://rust-lang.github.io/rust-clippy/master/#cast_lossles...
[5]: https://rust-lang.github.io/rust-clippy/master/#cast_possibl...
[6]: https://rust-lang.github.io/rust-clippy/master/#checked_conv...
[7]: https://rust-lang.github.io/rust-clippy/master/#char_lit_as_...
[8]: https://rust-lang.github.io/rust-clippy/master/#cast_sign_lo...
[9]: https://rust-lang.github.io/rust-clippy/master/#cast_precisi...
[10]: https://rust-lang.github.io/rust-clippy/master/#cast_possibl...
Yes it is. It's used all the time. There's a reason as_conversions defaults to Allow in clippy.
Of course, there are lots of situations where `as` is the wrong tool for the job, but I think it's a bit of a stretch to call `as` "not idiomatic". It's perfectly idiomatic in lots of situations.
Whether or not it should be idiomatic is a separate question.
IOW, is it currently unidiomatic? No, code reviewers won't generally look sideways at it. But it's certainly getting less idiomatic over time, and that trend doesn't seem likely to stop soon.
The docs, the reference, and the RFCs all regards “as” as a mistake that should not be used, and _many_ features have been introduced over the years to reduce the cases in which “as” is the only alternative.
There are cases in which there is currently no alternative, so people “must” use “as”. This does not imply that it is idiomatic to do so.
This looks very dangerous, because it essentially does the "nearest to right" thing. Say, you cast 256 to a u8, it's then saturated to 255. That's almost right, and a result might be wrong only by 0.5%. Much harder to detect than if it is set to 0.
It’s not supposed to. Type casting with ‘as’ is supposed to be lightweight and always succeed; there is no room in the type system to return an error. In case lossless casting is not possible, some value still has to be returned. Until now, this was outright UB — meaning the compiler is not even obligated to keep it consistent from one build to another. Saturating, while still not optimal, is at least deterministic.
> This looks very dangerous, because it essentially does the "nearest to right" thing.
That’s why the intention is to introduce more robust approximate conversion functions and eventually probably deprecate ‘as’ casts altogether. There has been a number of discussions about this; current disagreements seem to be about how to handle the various possible rounding modes.
Way worse than that. The compiler wasn't obligated to act like anything at all. It would be totally legal to compile it so that the first time the value was accessed you got 0, the next time you got 1 - within the same program execution, with no mutation of the value. That is the sort of thing that is observed behavior of UB in the worst cases, and why it's so terrible to just pretend that UB is innocuous.
There is: you panic, like in the array case.
That would have been much robust (at the cost of performance).
For better or worse, Rust 1.0 released with the philosophy that the `as` operator is for "fast and loose" conversions where accuracy is not prioritized; e.g. casting a u32 to a u8 would always risk silently truncating in the event the value was too large to represent. Over the years the language has added a lot of standard library support for bypassing the `as` operator entirely, and I think the prevailing opinion at this point might be that if they had the to do it all over again they might not have had the `as` operator at all, instead making do with a combination of ordinary error-checked conversion methods and the YOLO unsafe unchecked methods as seen here.
Which is to say: it's not that they technically couldn't have gone with the panic approach, but (performance implications aside) I think they'd rather just start moving away from `as` in general wherever possible.
If required to an an "unsound" label, that might be enough push for some developers to add their own explicit "if" guards or use another conversion method without having to deprecate "as".
As for requiring an additional speedbump (like e.g. a "lossy" label) here to guard against misuse, I think this proposal is overlooking something: Rust can't just abruptly break all code that currently uses `as` in order to demand that something like `lossy as` be used instead. Any removal would have to first have a very long period where `lossy as` is syntactically valid and where the compiler instead warns for people using raw `as`. But if the compiler is already emitting a mere warning for `as` that suggests a better alternative, then it could just as easily suggest a method like `.try_into()`, which exists today. And once you're having the compiler warn about changing `as` into something else, that's already indistinguishable from deprecating `as` in those instances, so there's no point trying to avoid it.
Alternatively one could just deprecate `as` for numeric conversions, although there are still some library holes that would need to be patched up (e.g. other than `as` I don't know of an existing single method to say that you want a fast integer conversion routine that merely truncates a u64 into a u32; right now the alternative is `try_into`, which does a runtime check and returns a Result). It might also exacerbate tensions with some people who for quite a while have been grumpy that Rust requires frequent explicit numeric conversions when doing things like indexing (which always requires a `usize` type, so you see `foo[bar as usize]` unless people want to always work with usizes directly); would these people be happier if that were `foo[bar.as_usize()]` instead, or would this all be blocked on a discussion about being more lenient with numeric conversions?
NaN to 0 is a bit more concerning, but inconvienence and compatibility need to be weighed against catching every error (no type system will catch every bug).
These attributes change in response to events in the game. When a civilization would reach the modern era, it's aggression attribute would be reduced by 2. Gandhi's aggression was reduced from 1 to 255 (underflow). He would rain down nukes on everything in sight, somewhat uncharacteristic of him.
Fans liked this so much that Firaxis maintained the same behaviour in later games.
Especially back in the 1980s and 1990s you'd get awful code that did things like averaging the two streams because wrapping sounds awful and the authors were ignorant of the theory and/or unaware that saturated addition is a thing.
You can tell when somebody did this because it means playing silence makes everything else quieter, or worse there's an arbitrary limit on how many streams are played and playing any one thing is very quiet because it's attenuated so as to never wrap.
Haiku the 1990s-style operating system did this for years, as did various Amiga music software.
Not sure what you mean here, and I don't have the standard at hand ATM, but I'm quite sure this is undefined behaviour in Fortran.
But yes, I agree defined behaviour is good. Undefined behaviour is occasionally good for optimization, at the cost of gray hairs for users.
Some things are well specified. Some things are mostly specified. Some things are still very much up in the air.
Though I try to always scrutinize any floating-point / integer conversions during code reviews. The default casting of a floating point value to integer is frequently not what you want, however. In the code we do, for example, you will usually round to the nearest integer instead, we don't normally need the more fancy rounding schemes.
To be honest... struggling to see why you'd do the former, outside of situations where you're happy with saturation, though I haven't thought about it a lot. Agreed that a consistent behaviour is a big help - I can work with "Rust does x in this scenario".