Concept proposal: Safely catching error

Olivier FAURE via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 8 07:02:24 PDT 2017


On Thursday, 8 June 2017 at 13:02:38 UTC, ag0aep6g wrote:
> Catching the resulting error is @safe when you throw the int* 
> away. So if f is `pure` and you make sure that the arguments 
> don't survive the `try` block, you're good, because f 
> supposedly cannot have reached anything else. This is your 
> proposal, right?

Right.

> I don't think that's sound. At least, it clashes with another 
> relatively recent development:
>
> https://dlang.org/phobos/core_memory.html#.pureMalloc
>
> That's a wrapper around C's malloc. C's malloc might set the 
> global errno, so it's impure. pureMalloc achieves purity by 
> resetting errno to the value it had before the call.
>
> So a `pure` function may mess with global state, as long as it 
> cleans it up. But when it's interrupted (e.g. by an 
> out-of-bounds error), it may leave globals in an invalid state. 
> So you can't assume that a `pure` function upholds its purity 
> when it throws an error.

That's true. A "pure after cleanup" function is incompatible with 
catching Errors (unless we introduce a "scope(error)" keyword 
that also runs on errors, but that comes with other problems).

Is pureMalloc supposed to be representative of pure functions, or 
more of a special case? That's not a rhetorical question, I 
genuinely don't know.

The spec says a pure function "does not read or write any global 
or static mutable state", which seems incompatible with "save a 
global, then write it back like it was". In fact, doing so seems 
contrary to the assumption that you can run any two pure 
functions on immutable / independent data at the same time and 
you won't have race conditions.

Actually, now I'm wondering whether pureMalloc & co handle 
potential race conditions at all, or just hope they don't happen.


More information about the Digitalmars-d mailing list