dip1000 and preview in combine to cause extra safety errors

Steven Schveighoffer schveiguy at gmail.com
Wed Jun 8 19:02:53 UTC 2022


On 6/8/22 1:09 PM, Mathias LANG wrote:
> On Wednesday, 8 June 2022 at 14:52:53 UTC, Steven Schveighoffer wrote:
>> ```d
>> string foo(in string s)
>> {
>>     return s;
>> }
>>
>> void main()
>> {
>>     import std.stdio;
>>     string[] result;
>>     foreach(c; "hello")
>>     {
>>         result ~= foo([c]);
>>     }
>>     writeln(result);
>> }
>> ```
>>
> 
> This has nothing to do with `-preview=in`.
> Change `foo`'s signature to:
>> string foo(scope string s)
> 
> And you'll see the bug, even without `-preview=dip1000`.

Yes, it has been noted by John.

But for some reason, this specific code doesn't fail with 
`-preview=dip1000` or `-preview=in`, but only when both are specified.

Apparently `in` under preview in doesn't really mean the same thing as 
`scope const`. So does it have nothing to do with preview in? simple 
experimentation says it does.

Note that `scope` arrays started being allocated on the stack in 
2.092.0, coincidentally the same release that added `-preview=in`.

> Why is this happening ? You correctly guessed, because the frontend 
> wrongfully lets the `string` go on the stack instead of allocating with it.

Whether it's right or wrong, it's a change that silently introduces 
memory corruption. It ought to produce a warning for such code. I'm not 
blaming anybody here for behavior that is probably correct per the spec. 
But is there no mechanism to be had for warning about this? D already 
doesn't allow returning a pointer to stack data, even in `@system` code. 
Doesn't this also qualify?

-Steve


More information about the Digitalmars-d mailing list