DIP1000 scope inference
Paul Backus
snarwin at gmail.com
Tue Oct 25 02:59:32 UTC 2022
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`
...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.
Still, this is a good illustration of how silently changing the
rules on people can have unintended consequences. If Walter ever
*does* consider adding dataflow analysis, overly-aggressive
"optimizations" like these could easily become obstacles in the
way of that goal.
[1]: https://issues.dlang.org/show_bug.cgi?id=20674
More information about the Digitalmars-d
mailing list