Understanding DIP 1000 semantics -- Where's the bug?

Sebastiaan Koppe mail at skoppe.eu
Tue Sep 24 08:05:54 UTC 2019

On Monday, 23 September 2019 at 20:50:30 UTC, ag0aep6g wrote:
> On Monday, 23 September 2019 at 19:11:46 UTC, Sebastiaan Koppe 
> wrote:
>> On Monday, 23 September 2019 at 18:46:40 UTC, Meta wrote:
>>> On Monday, 23 September 2019 at 18:39:03 UTC, Sebastiaan Koppe
>>>> Well, dip1000 doesn't do data-flow analyses. Which means the 
>>>> compiler doesn't see that `x` escapes through `a`.
>>> AFAICT, according to dip1000 this code should not allow the 
>>> result of `foo(x)` to be assigned to p, as it has a longer 
>>> lifetime. Likewise, it should not allow foo to return &x 
>>> without the parameter being annotated with `return`.
>> It does all those things when you replace the body of foo with 
>> just `return &x;`.
> Not really. When you do that, DMD rejects the `return` 
> statement, not the assignment `p = foo(x);`.

But that is what you want right? You want it to error out.

My reasoning is as follows, because dataflow analyses is missing, 
you need to simplify the body of foo to `return &x`. Then the 
compilers errors out saying you are escaping a reference and 
maybe you need to add the return annotation. After you fix that 
the compiler errors out saying "Error: address of variable x 
assigned to p with longer lifetime". Which is exactly what we 

Ergo, missing dataflow analyses.

> It works as expected when you mark the parameter with `return`. 
> This has nothing to do with missing flow analysis. It's just a 
> bug.

I agree that it will be better to get the 2 errors the first 
time, but is that a bug?

> ----
> @safe:
> int* fp(int* p) { return p; } /* This works. */
> int* fr(ref int r)  { return &r; } /* So this should work too. 
> */
> void main()
> {
>     int x;
>     fp(&x); /* This doesn't work. */
>     fr(x); /* So this shouldn't work either. */
> }
> ----

1) fp isn't `scope int*` so the function body compiles without 
2) you cannot return a reference to a local, so the function `fr` 
errors out correctly;
3) you cannot pass a reference to a local to a non-scope 
argument, so fp(&x) errors out correctly;
4) it is perfectly valid to pass a value to a ref parameter;

Still, I agree that it will be better to get the 2 errors the 
first time.

More information about the Digitalmars-d mailing list