[Pre-RFC] Zero-overhead exceptions

I would suggest to add Zero-Overhead Exception in Rust

Consider the following code:

union SomeFunctionMultipleError {
    err0: Error1,
    err1: Error2,
}

struct SomeFunctionFnError {
    index: u32,
    errors: SomeFunctionMultipleError,
}

fn some_function(i: i32) -> Result<i32, SomeFunctionFnError> {
    if i == 0 {
        Ok(2)
    } else if i == 1 {
        Err(SomeFunctionFnError{ index: 0, errors: SomeFunctionMultipleError {err1: Error1 {id0: 0, id1: 0, id3: 0}}})
    } else {
        Err(SomeFunctionFnError{ index: 0, errors: SomeFunctionMultipleError {err1: Error2 {id0: 0, id1: 0, id3: 0}}})
    }
}

union OtherFunctionMultipleError {
    err0: Error1,
    err1: Error2,
    err2: Error3,
}

struct OtherFunctionFnError {
    id: u32,
    errors: OtherFunctionMultipleError,
}

fn other_function(i: i32) -> Result<i32, OtherFunctionFnError> {
    if i == 0 {
        Ok(2)
    } else if i == 1 {
        Err(OtherFunctionFnError{id: 0, errors: OtherFunctionMultipleError {err0: Error1 {id0: 0, id1: 0, id3: 0}}})
    } else if i == 2 {
        Err(OtherFunctionFnError{id: 0, errors: OtherFunctionMultipleError {err0: Error2 {id0: 0, id1: 0, id3: 0}}})
    } else {
        Err(OtherFunctionFnError {id: 0, errors: OtherFunctionMultipleError {err0: Error3 {id0: 0, id1: 0}}})
    }
}

This is the code that could be generated by Zero-Overhead exceptions in Rust with following syntax feature:

fn some_function(i: i32) -> i32 throws Error1, Error2 {
    if i == 0 {
        2
    } else if i == 1 {
        Error1 {id0: 0, id1: 0, id3: 0}.throw
    } else {
        Error2 {id0: 0, id1: 0, id3: 0}.throw
    }
}

fn other_function(i: i32) -> i32 throws Error1, Error2, Error3 {
    if i == 0 {
        2
    } else if i == 1 {
        Error1 {id0: 0, id1: 0, id3: 0}.throw
    } else if i == 2 {
        Error2 {id0: 0, id1: 0, id3: 0}.throw
    } else {
        Error3 {id0: 0, id1: 0, id3: 0}.throw
    }
}

or even these errors could be deduced by compiler implicitly:

fn some_function(i: i32) -> i32 throws { // Implicitly throws Error1, Error2
    if i == 0 {
        2
    } else if i == 1 {
        Error1 {id0: 0, id1: 0, id3: 0}.throw
    } else {
        Error2 {id0: 0, id1: 0, id3: 0}.throw
    }
}

fn other_function(i: i32) -> i32 throws { // Implicitly throws Error1
    if i == 0 {
        2
    } else {
        Error1{id0: 0, id1: 0}.throw
    }
}

This nothing else syntactic sugar !! Behavior is the same !! C++ has the same proposal already http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r2.pdf

It is possible to implement and it is nothing else than syntactic sugar !!

1 Like

Wrapping like this is already a rfc https://github.com/rust-lang/rfcs/pull/2388

1 Like