komora-io / terrors

ergonomic and precise error handling built atop type-level set arithmetic
Apache License 2.0
211 stars 4 forks source link

Support implicit broadening using the try operator #11

Open Zk2u opened 7 months ago

Zk2u commented 7 months ago

Taking the example:

use terrors::OneOf;

struct Timeout;
struct AllocationFailure;

fn allocate_box() -> Result<Box<u8>, OneOf<(AllocationFailure,)>> {
    Err(AllocationFailure.into())
}

fn send() -> Result<(), OneOf<(Timeout,)>> {
    Err(Timeout.into())
}

fn allocate_and_send() -> Result<(), OneOf<(AllocationFailure, Timeout)>> {
    let boxed_byte: Box<u8> = allocate_box().map_err(OneOf::broaden)?;
    send().map_err(OneOf::broaden)?;

    Ok(())
}

// ...

Instead of using allocate_box().map_err(OneOf::broaden)?, we could implement Into for any subset of a OneOf so this can be simplified to just allocate_box()?, and the ? operator will implicitly broaden the error.

spacejam commented 3 weeks ago

I haven't found a way to support this using the current type system due to the requirement of having an additional Index type which allows the prolog-like type system to resolve correctly. If you or anyone else finds a way to support this with the stable From trait I would be very curious to see how it is possible.