Should (p - q) be disallowed in @safe code?
Timon Gehr
timon.gehr at gmx.ch
Sat Jan 3 21:10:05 UTC 2026
On 1/3/26 20:28, Walter Bright wrote:
> On 1/2/2026 3:17 PM, Timon Gehr wrote:
>> One memory-safe alternative semantics to UB would be: if arguments
>> point to different memory objects, you may get any result value. This
>> can still be implemented by your "practical effect" above, but now
>> it's memory safe (in isolation).
>
> I've said that it was memory safe all along.
You have both said that and then also said that I am obviously correct
when I say that UB is not memory safe. `p-q` is sometimes UB in C.
> I've said this proposal is
> extending @safe beyond memory safety to include bug detection of other
> things like p-q.
> ...
You said that, it's false. This is not merely a bug, it is UB if you
copy the C semantics.
>> You could have an even stronger semantics that also guarantees things
>> like `p is p+(q-p)`.
>
> I don't see any particular use for recognizing that.
It was an example of what even stronger semantics would possibly
guarantee, not a suggestion to detect something as a special case. In
this thread, you have often shot off on a tangent and then made a moot
unrelated claim along that tangent. I have to assume these are all the
result of misunderstandings.
> There are an
> infinite number of patterns that can be recognized, it's only useful to
> recognize ones that occur commonly.
> ...
There was literally someone in this thread who said they commonly rely
on this particular pattern and that it gives them better performance.
> BTW, the optimizer does recognize i+(j-i) as being just j, and it will
> do it for pointers to 1 byte objects. For pointers to int, the
> intermediate code looks like p+((q-p)/4)*4 which is not recognized.
> ...
The point was not about whether it is actually just the expression `j`,
the point was whether it will always result in the same value as `j`, no
matter how it got there (assuming the pointers were properly aligned).
>>> The only thing D can do is in @safe code simply disallow p-q, as
>>> there are good alternatives to do the equivalent thing.
>>
>> It's absolutely not the only possible thing. It is just one way (the C
>> way) to deal with the issue.
>
> Please explain the other ways.
I already have, in that same post. What is important for a `@safe`
construct is that it always has defined behavior. That behavior can be
nondeterministic, it just can't be undefined. You can for example say:
the semantics is that it will yield an arbitrary value or crash. That
would be a memory safe semantics. UB is not.
More information about the Digitalmars-d
mailing list