Bug 10562 – Cannot initialize arrays by an element value when the elements are fixed-length arrays
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-07-06T22:05:22Z
Last change time
2019-11-22T00:48:24Z
Keywords
pull
Assigned to
No Owner
Creator
Ali Cehreli
Comments
Comment #0 by acehreli — 2013-07-06T22:05:22Z
We know that arrays can be initialized by a single element value:
void main()
{
int value = 1;
int[2] a = value;
assert(a == [ 1, 1 ]);
}
The bug is that it does not work when the elements are fixed-length arrays themselves:
void main()
{
int[3] value = [ 1, 2, 3 ];
int[3][2] a = value; // <-- COMPILATION ERROR
assert(a == [ [ 1, 2, 3 ], [ 1, 2, 3 ] ]);
}
Error: mismatched array lengths, 6 and 3
On the other hand, the array can be initialized by an element-of-an-element:
void main()
{
// Note: This is the type of an element of array elements
int value = 1;
int[3][2] a = value;
assert(a == [ [ 1, 1, 1 ], [ 1, 1, 1 ] ]);
}
Is that a feature or perhaps a consequence of the reported bug?
Ali
Comment #1 by maxim — 2013-07-07T00:10:45Z
From the spec: "If a slice operator appears as the lvalue of an assignment expression, and the type of the rvalue is the same as the element type of the lvalue, then the lvalue's array contents are set to the rvalue. "
Assuming that single value initialization is a semantic equivalent of slice expression, the code should work.
Comment #2 by acehreli — 2019-11-08T06:45:00Z
I looked a little bit at function 'visit(AssignExp exp)' inside dmd/src/dmd/expressionsem.d. I think this is related to the fact that a static array initialization's left-hand expression treated as a dynamic array. This is evident in the following error message:
int[3][2][1] arr = 1.5; // Error: cannot implicitly convert expression `1.5` of type `double` to `int[]`
Note how the error message says int[] instead of int[3][2][1]. I suspect this is a bug due to code reuse in implementation.
Comment #3 by dlang-bot — 2019-11-21T21:47:51Z
@benjones created dlang/dmd pull request #10600 "Fix issue 10562 dont flatten arrays to 1D when " fixing this issue:
- Fix issue 10562 dont flatten arrays to 1D when being assigned to an array
https://github.com/dlang/dmd/pull/10600
Comment #4 by dlang-bot — 2019-11-22T00:48:24Z
dlang/dmd pull request #10600 "Fix issue 10562 dont flatten arrays to 1D when " was merged into master:
- 7c900d46148b0020b7f7e3b2c569faaf49869694 by Ben Jones:
Fix issue 10562 dont flatten arrays to 1D when being assigned to an array
https://github.com/dlang/dmd/pull/10600