dip1000 and preview in combine to cause extra safety errors

Meta jared771 at gmail.com
Wed Jun 8 19:07:00 UTC 2022


On Wednesday, 8 June 2022 at 18:44:28 UTC, 12345swordy wrote:
> On Wednesday, 8 June 2022 at 18:32:41 UTC, Timon Gehr wrote:
>> On 6/8/22 19:22, deadalnix wrote:
>>> On Wednesday, 8 June 2022 at 17:09:49 UTC, Mathias LANG wrote:
>>>> And you'll see the bug, even without `-preview=dip1000`.
>>>>
>>>> Why is this happening ? You correctly guessed, because the 
>>>> frontend wrongfully lets the `string` go on the stack 
>>>> instead of allocating with it.
>>>> ...
>>
>> Your code is literally calling this function:
>>
>> ```d
>> string foo(scope string s){ return s; }
>> ```
>>
>> This causes UB, therefore you can't blame the compiler 
>> frontend here.
>
> I got to say here, you shouldn't be able to compile that code 
> at all if it is going to shoot you in the foot unintentionally.
>
> - Alex

I believe this is because foo is not annotated with @safe, thus 
it's @system by default and you're allowed to do all kinds of 
unsafe things. Mark it @safe and the compiler will correctly 
complain:

```
@safe
string foo(in string s)
{
     return s; // Error: scope variable `s` may not be returned
}

void main()
{
     import std.stdio;
     string[] result;
     foreach(c; "hello")
     {
         result ~= foo([c]);
     }
     writeln(result);
}
```

In addition, changing `in` to `const return scope` makes the 
compiler aware that you intend to return the value, and thus it 
seems to somehow know not to re-use that stack space, and 
correctly prints ["h", "e", "l", "l", "o"].


More information about the Digitalmars-d mailing list