DIP1000 scope inference proposal

Steven Schveighoffer schveiguy at gmail.com
Thu Oct 27 01:26:53 UTC 2022


On 10/26/22 8:57 PM, Walter Bright wrote:
> On 10/26/2022 1:03 AM, Walter Bright wrote:
>> On 10/24/2022 6:35 PM, Steven Schveighoffer wrote:
>>> In a `@trusted` function today, without dip1000, the above is 
>>> perfectly reasonable and not invalid. Will dip1000 make it corrupt 
>>> memory?
>>
>> A very good question. Clearly, having code work when it is @safe, but 
>> cause memory corruption when it is marked @trusted, is the wrong 
>> solution. This should never happen. I'm not sure what the solution 
>> should be here.
>>
> 
> [Some more thinking about the problem]
> 
> The question is when is [1,2,3] allocated on the stack, and when is it 
> allocated on the GC heap?
> 
> Some points:
> 
> 1. in C it is allocated on the stack. D's behavior to allocate it on the 
> heap is kinda surprising in that light, even though D had such literals 
> before C did
> 
> 2. allocating on the heap means it is unusable in @nogc code
> 
> 3. when writing expressions, the only way to get it on the stack is to 
> assign it to a scope variable, which is inconvenient and inefficient
> 
> 4. it runs against the idea that the simpler code should be more 
> efficient than the complex code
> 
> Therefore, I suggest the following:
> 
>      [1,2,3] is always allocated on the stack
> 
>      [1,2,3].dup is always allocated on the heap
> 
> and thus, its behavior is not dependent on inference.
> 
> How we transition to this, we'll have to figure out.

Please no! We can allocate on the stack by explicitly requesting it:

```d
int[3] = [1, 2, 3];
```

The issue is the DRYness of it. This has been proposed before, just:

```d
int[$] = [1, 2, 3];
```

If we are going to fix something, let's fix this! It's backwards 
compatible too.

If anything, the compiler can just punt and say all array literals that 
aren't immediately assigned to static arrays are allocated on the heap. 
Then it's consistent.

Allocating array literals on the heap is *awesome*, please don't change 
that! D is one of the best learning languages for high-performance code 
because you don't have to worry at all about memory management out of 
the box. I'm actually OK with backends using stack allocations because 
it can prove they aren't escaping, why can't we just rely on that?

-Steve


More information about the Digitalmars-d mailing list