News for hackers. Stuff that matters.
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @02:39PM (#13273038)
A language's error-handling story is a central part of the experience of using that language. Especially if that language is a systems language.

Rust's error handling still seems unnecessarily verbose to me. A specific error type is only necessary if the program can handle the error in question. Rust has acknowledged this but I still don't want every function call in my code to be prefixed with "try!" or suffixed with "?!"

Rust error handling is also inefficient: in C++, if no error happens, then no code is run, whereas in Rust, even if no error happens a return code must be checked.

I will sadly continue to happily use C++ until Rust improves its error-handling story.

Re:Rust is more than safety by akiselev on Wednesday December 28, 2016 @03:39PM (#13273422)
> Rust error handling is also inefficient: in C++, if no error happens, then no code is run, whereas in Rust, even if no error happens a return code must be checked.

Just because you don't have to write the code doesn't mean that it doesn't exist! Exceptions are not a zero cost abstraction. Every C++ functional call that can throw adds several instructions of overhead to save information about the call stack and check the return value so even when you don't have an exception you still have the same amount of overhead as all Rust errors. Options are simple types that can often be optimized to the size of T in Some(T) and they're on the stack so worst case is you need an extra usize slot in your stack.

In the case of success, Rust is at least as efficient with errors as C++ but far more efficient when errors do occur.

Re:Rust is more than safety by cesarb on Wednesday December 28, 2016 @04:50PM (#13273985)
> Every C++ functional call that can throw adds several instructions of overhead to save information about the call stack and check the return value

That's not how it works (unless you're using 32-bit Windows). I wrote a long explanation using an old gcc on Linux at https://stackoverflow.com/questions/307610/how-do-exceptions...

Basically, calling a function that can throw doesn't save any information (other than what it already has to save to do the call), and it doesn't check any return value (other than any check on the return value you wrote yourself). Instead, the exception machinery uses compiler-generated tables, keyed to the return address, to direct the execution flow to the correct landing pad.

Re:Rust is more than safety by softc on Wednesday December 28, 2016 @05:13PM (#13274137)
In C++ with the Itanium ABI, exceptions only add overhead when thrown, not on every function call. In Rust, the result of every function call is checked.
Re:Rust is more than safety by Gankro on Wednesday December 28, 2016 @08:31PM (#13275096)
Agreed on this, but this is ignoring the much more subtle effect of unwinding: it introduces optimization barriers around every function that "might" throw.

As a basic example:

    x = 1
    something_that_can_fail()
    x = 2
With unwinding, the `x = 1` write must be preserved if whoever catches can observe it (and if that's unclear, it must be preserved conservatively).

The C++ STL riddled with complex machinery to try to work around this sort of thing because everything can throw. Copies, moves, you name it! Not even reallocating an array can be done with realloc unless non-throwingness can be proven.

If you try to make throwing "opt in" like Java, then you end up with nasty "throwingness polymorphism" problems and end up with constructs like Swift's "rethrows". By contrast, error propagation through normal values naturally composes because it's really easy to write code that generically handles return values.

Re:Rust is more than safety by softc on Thursday December 29, 2016 @04:00AM (#13276380)
Good point. Some responses:

Function calls themselves can force something like "x = 1" if x is observable from the callee.

In the case where "x = 1" is not observable from the catch block, then there is no effect. In cases where you would use "try!" in Rust, in the equivalent C++ cases the catch block wouldn't be able see local variables since it would be in a parent function call.

I think LTO largely eliminates this issue altogether since function bodies are visible to the optimizer in that case.

Re:Rust is more than safety by akiselev on Wednesday December 28, 2016 @05:22PM (#13274202)
I see, my knowledge of exceptions is quite out of date then. Regardless, both of those work out to the same performance because Rust's single compare will be optimized away by the branch predictor except when errors occur. In the error case, C++ exceptions would have a lot more overhead that you would have to explicitly opt into in Rust on a case by case basis (so no need to disable errors altogether).
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @05:35PM (#13274271)
Not every platform has a branch predictor, like low-cost embedded platforms, where bare metal languages like C++ are commonly used.

Error-case performance is negligible as it's much more rare (cf. Amdahl's law). If errors are common in a specific section of code, in C++ you have the option of using simple error-checking. You have no such counter-option in Rust.

Re:Rust is more than safety by akiselev on Wednesday December 28, 2016 @07:01PM (#13274751)
> Not every platform has a branch predictor, like low-cost embedded platforms, where bare metal languages like C++ are commonly used.

You're moving the goal posts. Itanium processors do have branch prediction so comparing C++ exceptions on Itanium to Rust on embedded architectures is meaningless. In embedded Rust, the worst case scenario is a compare between a constant and a register or a byte on the stack. Most non-ARM embedded platforms I've written firmware for barely have a three cycle multiply so a one cycle compare will be negligible except in the most extreme of cases (where you'd just write inline assembly anyway, no matter the language). On those platforms, you spend more time restoring registers than comparing the result of a call. On ARM processors, conditional execution behaves like a branch predictor on short compare jumps so there's again no overhead (except with value types, in which case Option adds 1-4 bytes for the None case on the stack).

Either way, Rust's error checking overhead is irrelevant. If your embedded environment is so resource constrained that Rust's error checking is too much overhead for you, then you certainly can't use C++ exceptions. They are too unpredictable without prohibitively expensive physical testing and tedious tuning of worst case code paths (unless you don't care about hard real time guarantees at all). If it's not, then it doesn't matter whether you use Rust errors or C++ exceptions because the overhead is a rounding error. We're not talking about something like reading memory from cache vs RAM or static vs dynamic dispatch where the difference in performance can be 10-1000x, we're literally talking about single digit cycles here.

> If errors are common in a specific section of code, in C++ you have the option of using simple error-checking. You have no such counter-option in Rust.

Yes, you do. You can unwind the stack manually and jump to the error handler, just like the C++ compiler does for you with exceptions. This is how the panic macro is implemented so all you have to do is modify its implementation (compiler-builtins crate) and create your own catch_unwind function. With the amount of time you'd spend typing "if (result != null)" or implementing an option type in C++, you can write your own exception implementation using Rust macros and traits. Rust developers made the right decision: "simple" error checking is the default with syntactic sugar to ease its use and if you really need those few extra cycles, you can make your own crate or compiler plugin that will give you the same features without polluting the rest of the ecosystem with a default error handling mechanism that is opaque, complex, and unsuitable for resource constrained real time systems.

Re:Rust is more than safety by softc on Thursday December 29, 2016 @04:03AM (#13276391)
The Itanium ABI is basically the reference ABI for all platforms, it doesn't only apply to Itanium.

Rust's error checking overhead is not unanimously irrelevant, it's not uncommon for functions to be called in tight loops.

I won't address your other comments since they are subjective and/or dependent on circumstances.

Re:Rust is more than safety by mmstick on Wednesday December 28, 2016 @04:08PM (#13273667)
The `?` operator is just syntax sugar for:

let value = match attempt_something() {

   Ok(value) => value,

   Err(error) => return SomeErr::Kind(error),
}

That way you only need to type

let value = do_something().map_err(SomeErr::Kind)?;

It was called for by the community because error checking is something that can happen multiple times within the same function. Simply passing the error up the chain and handling all your errors in a central location is highly convenient, especially when matching requires that you handle all cases.

Additionally, in no way is C++ more efficient at error handling that Rust. Rust is able to perform this with zero allocation costs.

Re:Rust is more than safety by softc on Wednesday December 28, 2016 @05:24PM (#13274211)
I understand exactly what "?" does, I just don't want to have to type it every time I call a function that can fail. Additionally I don't want to have to distinguish between which functions fail and which don't, I'd rather assume all functions fail and make sure my code is robust enough to handle failure at any point. This is my preference.

C++ is more efficient at error handling than Rust. In the common case of no error happening, Rust must check a return code, but C++ doesn't have to because of how exceptions are implemented in the Itanium ABI "zero-cost exceptions".

Re:Rust is more than safety by mmstick on Wednesday December 28, 2016 @05:37PM (#13274278)
There is no cost associated with Result/Option when no error is returned. The compiler is smart enough to understand when failure is not an option. Only when an error occurs does Rust act on it.

Additionally, it's nonsense to state that you don't want to handle errors when they occur, but want to write software that can handle failures at any point.

Software libraries should handle their errors properly in the event that an error is possible in a function so that users of that library can handle them. Binary applications should handle errors when they occur versus randomly throwing them into the air and hoping for the best.

The `?` operator is highly convenient in handling errors wherever they may occur whereby the error needs to be handled. You do not have to use the `?` operator if have other means of handling the error. In example, maybe you want to use a default value in the event of a failure:

let value = attempt_value().unwrap_or(default);

Or maybe you want to keep trying until it succeeds:

let value = loop {

    if let Some(value) = attempt_value() { break value }

    thread:sleep(Duration::from_millis(1));
};

It's up to you how you handle your errors. The Option and Result types have a lot of methods for handling, such as and_then and or.

Re:Rust is more than safety by dbaupp on Wednesday December 28, 2016 @05:53PM (#13274374)
You're being too enthusiastic/wrong: there is a cost to Result and Option even in the good case. There still has to be a branch to check if there actually was no error. Result and Option are similar to error codes in C and have a similar cost/benefit trade-off, although of course with all the ADT/type-safety goodness.
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @05:47PM (#13274342)
Hmm no. Rust always issues a compare instruction after a function call to verify if it was successful or not. In a function that can fail depending on runtime conditions, the compiler is unable to elide such a check.

Also I don't think my error handling method is nonsense as it seems to work for all the code I write. If I don't handle an error at local function scope, my intent is to handle it higher up the stack.

Re:Rust is more than safety by akiselev on Wednesday December 28, 2016 @04:29PM (#13273836)
The best part is that you can use Into/From conversion traits and use a different error type all through the call chain. A bunch of functions returning error type A and calling functions with error types B, C, D, and E can all just pass through the errors even though they return a different type. You implement the conversion trait once for each error and then it just works for all functions with no other boilerplate.
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @06:20PM (#13274546)
With this method, do you have to implement the From trait for every pair of errors that can be propagated up the stack?
Re:Rust is more than safety by sidlls on Wednesday December 28, 2016 @02:46PM (#13273093)
I have almost the exact inverse view: when I write C++ code, I shed a tear if I can't disable exceptions and use something very analogous to Rust's Result type. I can't tell you how many times I've written some version of 'class Result<T> { union {int, T} }' (obviously, that's illustrative, given all the extra work that has to go into writing a proper tagged-union in C++) for use with C++ code at jobs I've had in the past. Rust's implementation here is great, in my opinion.
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @02:59PM (#13273166)
Just to clarify, In this specific case, I think we're talking about interface, not implementation.

Your preference is fair, since interface is a subjective issue. Personally, I find it more convenient to simply assume all code can encounter a error. Given that assumption, I find it redundant to add extra syntax to fail on unhandled errors.

Re:Rust is more than safety by lacampbell on Wednesday December 28, 2016 @03:22PM (#13273312)
As an aside: I'm curious as to why you'd implement a Result type in C++ as a tagged union where you have to manually branch on the tag, and not as an abstract class with two children.
Re:Rust is more than safety by dbaupp on Wednesday December 28, 2016 @03:47PM (#13273485)
The union avoids requiring an allocation for, say, returning a Result.
Re:Rust is more than safety by lacampbell on Wednesday December 28, 2016 @04:02PM (#13273623)
I am not sure what using an object vs using a struct with an enum + a union has to do with allocation. My C++ is rusty (no pun intended).
Re:Rust is more than safety by dbaupp on Wednesday December 28, 2016 @05:56PM (#13274390)
The equivalent of a function returning Result<T, E> in Rust would be returning something like unique_ptr<ResultBaseClass<T,E>> because the two subclasses have different sizes and thus can't be returned directly (or else one will be object slicing). The struct version stores everything inline from the start (it has a single static size) and so can be returned without needing a pointer.
Re:Rust is more than safety by lacampbell on Wednesday December 28, 2016 @07:38PM (#13274895)
My C++ skills have atrophied worse than i thought - I completely forgot you can't return an abstract class by value.
Re:Rust is more than safety by sidlls on Wednesday December 28, 2016 @03:24PM (#13273321)
I find it easier to reason about.
Re:Rust is more than safety by lacampbell on Wednesday December 28, 2016 @03:42PM (#13273440)
Interesting. I tend to view ADT as syntax sugar for a shallow class hierarchy of small immutable objects with no encapsulation or behaviour.
Re:Rust is more than safety by oconnor663 on Wednesday December 28, 2016 @02:44PM (#13273071)
> Rust error handling is also inefficient: in C++, if no error happens, then no code is run, whereas in Rust, even if no error happens a return code must be checked.

In this sense Rust's error handling is just like C (though harder to forget to check). Would you say C++ is more efficient than C in error handling?

Re:Rust is more than safety by softc on Wednesday December 28, 2016 @02:54PM (#13273135)
Yes I would. In modern C++ we use exceptions and RAII for automatic cleanup.
Re:Rust is more than safety by mmstick on Wednesday December 28, 2016 @04:05PM (#13273633)
Exceptions have high cost so I don't see where you are coming from. Rust's RAII goes further along than C++'s. C++ is playing a game of catchup to steal the move semantics from Rust.
Re:Rust is more than safety by olejorgenb on Wednesday December 28, 2016 @05:24PM (#13274215)
According to http://stackoverflow.com/a/13836329/1517969 modern c++ exceptions are free when no throw occurs.
Re:Rust is more than safety by mmstick on Wednesday December 28, 2016 @05:29PM (#13274240)
In addition, Rust Results/Options are free when no throw occurs. So the argument is moot.
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @05:38PM (#13274285)
No they aren't, you must issue a compare instruction to verify the result was successful.
Re:Rust is more than safety by oconnor663 on Saturday January 07, 2017 @05:37PM (#13347077)
Do you know whether branch prediction makes them effectively free, in places where the result is almost always successful?
Re:Rust is more than safety by softc on Wednesday December 28, 2016 @05:28PM (#13274235)
Exception handling in C++ is absolutely zero-cost when no exception occurs. Look up the Itanium ABI. In Rust, even if no error occurs, the return value must still be checked.

Additionally, Move semantics were borrowed from C++, not the other way around.