Is the following well defined and allowed?

ag0aep6g anonymous at example.com
Fri Mar 2 16:22:03 UTC 2018


On 03/02/2018 03:39 PM, Steven Schveighoffer wrote:
> On 3/1/18 5:27 PM, ag0aep6g wrote:
[...]
> No, I'm looking at the source code.
> 
> At the very basic level, you have this:
> 
> assert(foo == 0);
> 
> Or whatever other condition you have. What this does is gives the 
> compiler leeway to ASSUME foo is 0 at this point. It can make any number 
> of optimizations assuming this. If foo is NOT equal to 0 at this point, 
> then it is a program error, and the assumptions may cause bad things to 
> happen.
> 
> When you compile in normal mode, this assert causes an Error to be 
> thrown, before your code can do any damage.
> 
> When you compile without asserts, this causes undefined behavior.

Now you're looking beyond the source code. There's no "normal mode" or 
"without asserts mode" in D source code. What you've got in the D code 
is @safe and @system.

Looking at it your way makes sense when the question is how the actual 
generated executable will behave. But I think it's also valuable to look 
at the language in isolation, without compiler settings.

I'd put it this way:

1) @system code may have UB. For example, out-of-bounds accesses have UB 
in @system code.

2) A compiler may give guarantees on what it does with specific 
instances of UB. For example, DMD guarantees that it throws an Error on 
out-of-bounds accesses, unless you compile with -release. This makes it 
effectively implementation defined behavior. You can rely on this. But 
when considering the source code in isolation, it still has UB.

3) @safe code cannot have UB. This is a strong guarantee. This cannot be 
affected by compiler switches without violating the spec.

[...]
> I extend this same treatment and logic to all checks: contracts, bounds 
> checks, overlapping slice assign checks, etc. To me, they aren't any 
> different than asserts. They aren't any different if they are in @safe 
> code or @system code.

I don't agree with the @safe/@system part. @safe code must not exhibit 
UB. That's the point of the attribute.

Checks that would fail may cause UB in @system code, but they can't be 
allowed to cause UB in @safe code. Because nothing can be allowed to 
cause UB in @safe code.

[...]
> I agree, I think we should remove the option to disable bounds checks on 
> @safe code, in any way. It's too dangerous. If you want performance that 
> comes without bounds checks, use a trusted escape, or write system code.

I'm not going to argue against that, obviously.


More information about the Digitalmars-d mailing list