Bug 22982 – Can't copy scope range elements into a returned array
Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2022-04-04T09:09:46Z
Last change time
2022-04-07T15:22:55Z
Keywords
rejects-valid, safe
Assigned to
No Owner
Creator
Atila Neves
Comments
Comment #0 by atila.neves — 2022-04-04T09:09:46Z
This code should, but doesn't, compile:
---------------------
void main() @safe pure {
import std.range : only;
scope rng = only("foo", "bar");
oops(rng);
}
auto oops(Range)(return scope Range range) @safe {
import std.range : ElementEncodingType;
ElementEncodingType!Range[] result;
foreach(e; range)
result ~= e;
return result;
}
------------------------
d.d(13): Error: scope variable `e` may not be copied into allocated memory
d.d(6): Error: template instance `d.oops!(OnlyResult!(string, string))` error instantiating
Comment #1 by dkorpel — 2022-04-04T09:20:42Z
The `only` range here is essentially a static array of `scope` strings. You can't put scope strings in a dynamic array, because `scope` semantics aren't transitive, so the error is correct.
Comment #2 by atila.neves — 2022-04-07T14:53:58Z
I don't know if transitivity has anything to do with it, since the element is scope.
Conceptually, I think return scope on `only` should allow me to return an array from it.
Comment #3 by ag0aep6g — 2022-04-07T15:22:55Z
(In reply to Atila Neves from comment #2)
> I don't know if transitivity has anything to do with it, since the element
> is scope.
>
> Conceptually, I think return scope on `only` should allow me to return an
> array from it.
`scope` is not a type qualifier. You cannot have a dynamic array of `scope` things. `scope` always applies to the outermost indirection(s) of a variable (ignoring `ref`).
If you think `scope` should work differently, you will probably have to re-design the whole thing.