Bug 23297 – You Can Assign a dstring to a dchar[] if Both Sides of the Expression are Slices
Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2022-08-18T15:31:21Z
Last change time
2022-08-18T19:09:10Z
Assigned to
No Owner
Creator
Ruby The Roobster
Comments
Comment #0 by rubytheroobster — 2022-08-18T15:31:21Z
The following code fails, like it should:
```d
void main()
{
dchar[] a; //asset(typeof(a).stringof == "dchar[]")
dstring b = "a"d; //assert(typeof(b).stringof == "immutable(dchar)[]");
a = b; //ERROR: VIOLATES THE TYPE SYSTEM
}
```
However, the following code compiles and runs:
```d
void main()
{
import std.stdio;
dchar[] a = "ab".dup;
writeln(typeof(a[0 .. $-1]).stringof); //Prints 'dchar[]'
writeln(typeof(a[1 .. $]).stringof); //Prints 'immutable(dchar)[]'
a[0 .. $-1] = a[1 .. $].idup; //Compiles, but WRONG
--a.length;
writeln(a); //Prints 'b' to stdout
}
```
Given that the first example fails, the second example should also fail and output a similar error.
Comment #1 by dfj1esp02 — 2022-08-18T15:53:07Z
The second example should work, it's array copy - copies elements from one array to another. The first example is slice assignment that would refer to the same array.
Comment #2 by dfj1esp02 — 2022-08-18T15:57:23Z
I guess, documentation can be improved here, it mentions only array copy for static array and not for slices.
Comment #3 by rubytheroobster — 2022-08-18T16:48:52Z
(In reply to anonymous4 from comment #1)
> The second example should work, it's array copy - copies elements from one
> array to another. The first example is slice assignment that would refer to
> the same array.
Can you be more clear? I think you got the two examples mixed up.
Also, the second example compiles with wchar and char, not just dchar, and the following works:
```d
void main()
{
wchar[] a = "ab"w.dup;
wchar[]b = a.dup;
import std.stdio;
writeln("Type of a[0 .. $-1]: ", typeof(a[0 .. $-1]).stringof);
writeln("Type of b[1 .. $].idup: ", typeof(b[1 .. $].idup).stringof);
a[0 .. $-1] = b[1 .. $].idup; //See? Two completely different arrays.
--a.length;
writeln(a);
writeln(typeof(a).stringof);
}
```
This is assigning an array of immutable wchars to an array of mutable wchars. No matter how you put it, this is a violation of the type system.
Comment #4 by kinke — 2022-08-18T17:55:56Z
(In reply to anonymous4 from comment #2)
> I guess, documentation can be improved here, it mentions only array copy for
> static array and not for slices.
IMO fine: https://dlang.org/spec/arrays.html#array-copying
Comment #5 by rubytheroobster — 2022-08-18T19:09:10Z
(In reply to kinke from comment #4)
> (In reply to anonymous4 from comment #2)
> > I guess, documentation can be improved here, it mentions only array copy for
> > static array and not for slices.
>
> IMO fine: https://dlang.org/spec/arrays.html#array-copying
Okay. Now I see why this isn't a bug.