purity question
Brad Roberts via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun May 28 18:39:02 PDT 2017
On 5/28/2017 6:27 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
> On Monday, May 29, 2017 01:01:46 Stefan Koch via Digitalmars-d-learn wrote:
>> On Monday, 29 May 2017 at 00:53:25 UTC, Brad Roberts wrote:
>>> On 5/28/2017 5:34 PM, Jonathan M Davis via Digitalmars-d-learn
>>>
>>> wrote:
>>>> On Sunday, May 28, 2017 16:49:16 Brad Roberts via
>>>>
>>>> Digitalmars-d-learn wrote:
>>>>> Is there a mechanism for declaring something pure when it's
>>>>> built from
>>>>> parts which individually aren't?
>>>>>
>>>>> string foo(string s)
>>>>> {
>>>>>
>>>>> // do something arbitrarily complex with s that doesn't
>>>>>
>>>>> touch
>>>>> globals or change global state except possibly state of the
>>>>> heap or gc
>>>>>
>>>>> return s;
>>>>>
>>>>> }
>>>> <snip lecture> you can cast </snip lecture>
>>> Ok, so there essentially isn't. I'm well aware of the risks of
>>> lying to the compiler, but it's also not sufficiently smart to
>>> unravel complex code. Combined with there being interesting
>>> parts of the standard libraries that themselves aren't marked
>>> pure, there's a real need for escape hatches. A simple
>>> example: anything that has a malloc/free pair.
>> There is
>>
>> void[] myPureMalloc(uint size) pure @trusted nothrow @nogc
>> {
>> alias pure_malloc_t = pure nothrow void* function(size_t size);
>> return (cast(pure_malloc_t)malloc)(size)[0 .. size];
>> }
> There was a whole discussion or 3 is PRs about making malloc pure, and IIRC,
> it was done and then decided that it wasn't safe to do some for one reason
> or another (IIRC, it had to do with what would happen when calls were
> elided, because the caller was strongly pure, but I'm not sure). So, I'd be
> _very_ careful about deciding that it was safe to call malloc in pure code.
> I expect that it's just fine in some contexts, but it's easy enough to screw
> up and mark something as pure when it really shouldn't be because of some
> detail you missed that you should be _really_ careful about decided to cast
> to pure.
>
> - Jonathan M Davis
That's one reason I explicitly referenced malloc/free pairs. It's a lot
easier to be sure that those together aren't violating purity.
More information about the Digitalmars-d-learn
mailing list