scope(exit) with expected library

Steven Schveighoffer schveiguy at gmail.com
Wed Aug 25 15:30:57 UTC 2021


On 8/25/21 10:58 AM, WebFreak001 wrote:

> 
> Hm I'm not quite seeing how the error handler is related to an "Expected 
> type interface" that the compiler could expect.

This would be without compiler changes.

> Currently with exceptions the scope things are implemented using 
> try-catch-finally, this would be even simpler:
> 
> ```d
> scope(exit) exit();
> scope(success) success();
> scope(failure) failure();
> 
> return something();
> ```
> 
> lowers to
> 
> ```d
> auto ret = something();
> if (ret.isError) failure();
> if (!ret.isError) success();
> exit();
> return ret;
> ```
> 
> for all return statements.
> 
> I might be missing some obvious drawbacks here but I think this sounds 
> reasonable and comparable with the try-catch-finally lowering.

It does sound pretty reasonable. But overloading these existing features 
might make things confusing.

> 
> As Paul Backus suggested the compiler could check if the return type has 
> for example `is(typeof(return.isError) : bool)` and maybe also if the 
> function is `nothrow`.

Another approach is to let the compiler deal with the error handling and 
not muddy your return type. Swift does something similar, where it 
rewrites the throw/catch into a standard return and doesn't do actual 
thrown exceptions. There are some caveats, but if we could fit this kind 
of error handling into mostly-similar syntax (i.e. the same ease of 
exceptions without the actual problems that exceptions and stack 
unwinding bring), it might make things much easier to transition.

-Steve


More information about the Digitalmars-d-learn mailing list