[Issue 8185] Pure functions and pointers

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Jun 2 08:57:17 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=8185



--- Comment #6 from Denis Shelomovskij <verylonglogin.reg at gmail.com> 2012-06-02 19:59:12 MSD ---
(In reply to comment #4)
> (In reply to comment #3)
> >     assert(res == f(arr.ptr + 1)); // *p isn't changed
> Might fail, f is allowed to return cast(int)p.

Am I understanding correct that:
---
int[] f() pure;
int g(in int[] a) pure;
int gs(in int[] a) @safe pure;

void h()
{
    assert(g(f()) == g(f()));   // May or may not pass
    assert(gs(f()) == gs(f())); // Should pass
}
---
?

> >     arr[1] = 7;
> >     assert(res == f(arr.ptr)); // neither p nor *p is changed
> Must pass,...

So this code is invalid:
---
void f(int* i) pure @safe // or unsafe, doesn't matter
{ ++i[1]; }
---
and this is invalid too:
---
struct MyArray {
    int* p;
    size_t len;

    ...

    int opIndex(size_t i) pure @safe // or unsafe, doesn't matter
    in { assert(i < len); }
    body {
        return p[len];
    }
}
---
?

And this is valid:
---
void f(int* i) pure @safe // or unsafe, doesn't matter
{ ++*i; }
---
?

> reading/modifying random bits of memory inside pure functions is
> obviously a bad idea. Bad idea meaning that pointer arithmetic is disallowed in
> @safe code anyway, and in @system code, you as the programmer are responsible
> for not violating the type system guarantees – for example, you can just call
> any impure function in a pure context using a cast. This also means that e.g. C
> string functions cannot not be pure in D.

I'm a bit confused because I didn't mention @safe attribute. If you have a time
I'd like to see about @safe/unsafe pure functions differences in your article
because it looks like these things are really different.

> > The second assert is here according to
> > http://klickverbot.at/blog/2012/05/purity-in-d/.
> Then this aspect of the article is apparently not as clear as it could be –
> thanks for the feedback, I'll incorporate it in the next revision.

Not sure, my English is rather bad so I could just misunderstand something.

> Do you disagree with any of these points? If so, I'd be happy to provide a more
> in-depth explanation of my view, so we can clarify the spec afterwards.


`void f(void*) pure;` is still unclear for me. What can it do? What can it do
if it's @safe?

And I completely misunderstand why pure functions can't be optimized out as
Steven Schveighoffer sad in druntime pull 198 comment:
> The fact that it returns mutable makes it weak pure (the optimizer cannot remove any calls to gc_malloc)
(yes, this is a general question, not pointers only)

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list