regexex, enforce and purity

Jonathan M Davis jmdavisProg at gmx.com
Sun Sep 9 18:25:11 PDT 2012


On Sunday, September 09, 2012 21:04:58 monarch_dodra wrote:
> So I'll rephrase my 1):
> Why the difference in behavior regarding the return value? Is it
> just historical/no real reason, or is there something for me to
> learn here?

Just look at the examples. You're supposed to be able to use enforce to 
enforce that the value is explicitly convertible to true and then use the 
value all in one expression. assert gets compiled out in -release mode, so 
that sort of behavior doesn't make sense for assert. enforce on the other hand 
is _always_ there, so using it as part of a larger expression can make sense. 
I don't think that it gets used that way very often though, because it only 
makes sense when testing whether the result is convertible to true, and most 
expressions used with enforce or already boolean expressions (in which case, 
using the value aftewards usually doesn't make sense).

The problem here is that you seem to have found a way to use an impure 
function inside of enforce. @safe and pure were added onto it with the idea 
that it was impossible for it to be otherwise.

T enforce(T)(T value, lazy const(char)[] msg = null, string file = __FILE__,
                    size_t line = __LINE__) @safe pure
{
    if (!value) bailOut(file, line, msg);
    return value;
}

It's not calling any functions on value, so in theory, it shouldn't require 
any functions on T to be either @safe or pure. But it looks like the 
destructor is being called (which I guess isn't surprising if you really think 
about it), and since an explicit cast is happening (in the if, !value becomes 
!cast(bool)value), the cast operator would probably need to be @safe and pure 
as well. It's a bug in enforce. Since it apparently _is_ possible for non-
@safe and non-pure functions to be called within enforce, it should use 
attribute inferrence for them rather than explicitly listing them. Please 
report it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list