On Wednesday, 25 August 2021 at 14:42:07 UTC, Steven
Schveighoffer wrote:
On 8/25/21 10:22 AM, Paul Backus wrote:
On Wednesday, 25 August 2021 at 14:04:54 UTC, WebFreak001
wrote:
[...]
Probably the only principled way to make this work would be to
define some kind of "concept"/structural interface that's
recognized by the compiler to mean "this is an error-handling
type", in the same way that the compiler recognizes
`empty`/`front`/`popFront` to mean "this is an iterable type".
Even then, it would require some pretty invasive language
changes (and some pretty gnarly code in the compiler), but
it's at least *theoretically* possible.
I think it's possible to work with some mechanics that aren't
necessarily desirable. Something like:
```d
ErrorHandler error = registerErrorHandler;
error.onFailure({writeln("division failed");});
error.onSuccess({writeln("division succeeded");});
...
```
On returning `err`, the registration would trigger a flag
saying an error is occurring, and call the right callback when
`ErrorHandler` is destructing. The cleanup of the return value
would clean up the error condition. It would be messy and
likely brittle.
Hm I'm not quite seeing how the error handler is related to an
"Expected type interface" that the compiler could expect.
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.
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`.