Bug 16357 – cast(T[])[x] casts x to T instead of [x] to T[]

Status
RESOLVED
Resolution
WONTFIX
Severity
normal
Priority
P3
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-08-07T00:21:17Z
Last change time
2023-11-08T16:16:43Z
Keywords
pull, spec, wrong-code
Assigned to
No Owner
Creator
Vladimir Panteleev

Comments

Comment #0 by dlang-bugzilla — 2016-08-07T00:21:17Z
////////////// test.d ////////////// void main() { uint x; ubyte[] data = cast(ubyte[])[x]; assert(data.length == 4); } //////////////////////////////////// This is surprising, because if the expression is split up into: auto arr = [x]; ubyte[] data = cast(ubyte[])arr; then the result is as expected (an array with 4 elements).
Comment #1 by dlang-bugzilla — 2019-02-17T21:33:00Z
*** Issue 19683 has been marked as a duplicate of this issue. ***
Comment #2 by ag0aep6g — 2021-06-21T08:52:59Z
*** Issue 22055 has been marked as a duplicate of this issue. ***
Comment #3 by schveiguy — 2023-10-04T22:19:10Z
This is technically in the spec: https://dlang.org/spec/expression.html#cast_array_literal Quoting: ``` When array literals are cast to another array type, each element of the array is cast to the new element type. ``` But I don't know if the spec (which only shows casting arrays with elements of value 1) or this issue (which has elements of value 0) explores the destructive nature of the current implementation: ```d void main() { uint x = 0x12345; ubyte[] data = cast(ubyte[])[x]; assert(data == [0x45]); // we lost the extra bytes! } ``` My thought is that this should either be an error, or a warning in the spec is warranted.
Comment #4 by dlang-bot — 2023-10-06T14:51:03Z
@ntrel updated dlang/dlang.org pull request #3701 "[spec] Array literal can implicitly convert to an expected type" fixing this issue: - Show overflow in example Fix Issue 16357 - cast(T[])[x] casts x to T instead of [x] to T[]. https://github.com/dlang/dlang.org/pull/3701
Comment #5 by nick — 2023-10-06T14:55:27Z
I've made a PR to update the spec. I don't think we can make that an error without risking existing code breakage.
Comment #6 by dlang-bot — 2023-11-08T10:32:35Z
dlang/dlang.org pull request #3701 "[spec] Array literal can implicitly convert to an expected type" was merged into master: - 4e8db30f0bf3c330c3431e83fe8a75f843b40857 by Nick Treleaven: Show overflow in example Fix Issue 16357 - cast(T[])[x] casts x to T instead of [x] to T[]. https://github.com/dlang/dlang.org/pull/3701
Comment #7 by schveiguy — 2023-11-08T16:16:43Z
I'm changing this to WONTFIX because the original bug report is against the behavior, not that it wasn't explained properly.