Pure functions and pointers (yes, again)
travert at phare.normalesup.org
Wed Jul 4 02:21:35 PDT 2012
Denis Shelomovskij , dans le message (digitalmars.D:171072), a écrit :
> Since issue 8185 has been closed, I'm still very confused. I just
> understood that endless discussion doesn't result in anything.
> See example from http://d.puremagic.com/issues/show_bug.cgi?id=8185#c40
> int f(size_t p) pure
> return *cast(int*) p;
> void g(size_t p, ref size_t) pure
> ++*cast(int*) p;
> void h(size_t a, size_t b) pure
> int res = f(a);
> g(b, b);
> assert(res == f(a)); // may fail, no guaranties by language!
> void main()
> int a;
> h(cast(size_t) &a, cast(size_t) &a);
> Jonathan M Davis (whose documentation correcting pull closed the issue)
> told me that this code result in undefined behaviour. What _exectly_
> language rule this violates? I don't see this rule, but if there is no
> such rule, how can we treat anything as strongly pure function?
Casting a value to a pointer clearly subvert the type system. A value
with no reference (like size_t) is convertible to immutable, but a
pointer cannot. Thus, a function with f's signature is strongly pure,
but it is not if takes an int*. That's how you can create a bug.
The same issue occurs if you 'create' a pointer by illegal pointer
arithmetic for instance: this is undefined behavior. Creating and using
any kind reference by casting is undefined. That's not only a purity
problem, it is a safety, a garbage collection, an and optimisation
issue. In your case, you know what you ar doing regarding safety and
garbage collection. Fine. But you do not respect optimisations linked
with purity. Too bad, you can't ignore that the compiler is going to
make assumptions regarding your datas types.
What change would you expect in the langage? making pure function
automatically @safe? That may not be such a ba idea. However, that is
not even enough, you could still create bug from optimizations with
casting outside the pure function (for instance, you could alias
variables that should not be aliased).
The only possibility to completely avoid this kind of bug is to forbid
either optimization or casting. That's not going to happen in D.
More information about the Digitalmars-d