Should (p - q) be disallowed in @safe code?

Timon Gehr timon.gehr at gmx.ch
Fri Jan 2 02:11:41 UTC 2026


On 1/1/26 23:14, Walter Bright wrote:
>  > 1/1/2026 12:57 PM, Timon Gehr wrote:
>> It's one question whether you have to mark it `@trusted` for it to 
>> type check, it's another question whether you are allowed to mark it 
>> `@trusted` (i.e., whether it is actually memory safe).
> 
> @trusted only applies to the interface, not the code itself.
> 
>> In C, I think adding an integer to a pointer aiming to get a result 
>> that points to a different memory object entirely would just be UB.
> 
> You're right.
> 
> 
>> I.e., there is some potential for `q+(p-q)` to do something other than 
>> give you `p` unless glue code and backends are careful to handle it as 
>> intended.
> 
> My proposal would not affect that - the frontend would diagnose p-q as 
> an error in @safe code.
> ...

I understand, but your latest point was "just put `@trusted` on it".


Let's say the frontend now treats `p-q` as `@system`, and there is not 
even any documentation of what its semantics is supposed to be.

Do you believe with this background, alternative backends will in the 
future be more likely to:

- treat `p-q` as UB when different memory objects are involved

- treat `p-q` as defined behavior when different memory objects are involved

I just think the overall effect of this will be to cause confusion about 
what is allowed among all parties involved. I think it's better to stick 
to banning language constructs from `@safe` if they can actually exhibit UB.

> 
>> As far as I can tell, such nuances are not documented in the D spec 
>> and so it would be defensible for GDC and LDC to assume it's just 
>> supposed to mimic C behavior. Whether the backends actually do end up 
>> breaking assumptions like they would be allowed to is still another 
>> question.
> 
> I designed the semantics of D fully aware of the reality that the usable 
> backends (including mine) were designed for C, and that to not do so 
> would be language suicide.
> 
> (And it's not just the backends, there are the debuggers, etc.)

And yet it seems for `p-q` you differed.


More information about the Digitalmars-d mailing list