DIP1000 scope inference
Steven Schveighoffer
schveiguy at gmail.com
Tue Oct 25 13:44:34 UTC 2022
On 10/24/22 10:59 PM, Paul Backus wrote:
> On Tuesday, 25 October 2022 at 02:38:02 UTC, Steven Schveighoffer wrote:
>> OK, what about this?
>>
>> ```d
>> int[] mkarr() @trusted {
>> int[3] arr = [1, 2, 3];
>> int[] other = [4, 5, 6];
>>
>> auto foo = other;
>> other = arr[];
>> return foo;
>> }
>> ```
>>
>> `other` is inferred as `scope` (along with `foo`), because it touches
>> `arr[]` later (but after it was pointing at what should have been heap
>> memory). So does that count as possible for stack allocation, or is it
>> still heap allocated?
>
> When I compile the above with `@safe` and `-preview=dip1000`, I get
>
> Error: reference to local variable `arr` assigned to non-scope `other`
OK, I misread the error here, it's the same on run.dlang.io. But we did
just go through an exercise where a struct not labeled scope is inferred
scope not because of its declaration, but because of later things done
with it. It doesn't seem to be the case here.
>
> ...using both DMD 2.100.2 and DMD master. So `scope` is not actually
> being inferred here, and the array is allocated on the heap.
>
> My expectation is that `scope` will probably *never* be inferred for
> `other`, because doing multi-step inference like this requires dataflow
> analysis in the general case, which is something Walter wants to avoid
> (see discussion in [issue 20674][1]). So I don't think you have anything
> to worry about.
My biggest concern is that this inference takes priority over what is
actually written, and then can cause memory problems to occur in code
that seemingly reads like it shouldn't cause memory problems.
I'm trying to find a hole because I'm worried about that hole showing up
without intention later (especially with the way the compiler can inline
and rewrite code for optimization). The compiler doing things that are
not checkable (I know of no way to introspect that something is scope
inferred), hard to describe, and impossible to prevent makes things
uncomfortable. Especially if the compiler might make disastrous
decisions based on that inference.
It would be relieving to have some rule that says "any data inferred
scope inside a @system or @trusted context without explicitly being
declared scope shall not result in memory allocations hoisting to the
stack". I can deal, begrudgingly, with compiler errors that are
misguided. I can't deal with memory errors caused by the compiler
knowing better than me.
-Steve
More information about the Digitalmars-d
mailing list