Bug 12611 – Deprecation and then error for implicit casts that lose precision in foreach index loops
Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2014-04-21T23:33:08Z
Last change time
2020-09-02T09:46:32Z
Keywords
accepts-invalid
Assigned to
No Owner
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2014-04-21T23:33:08Z
In this program the assignment to x1 is accepted, but the assignments to x2 and x3 are refused:
// Program #1.
void main() {
int[200] data1;
ubyte x1 = data1.length;
int[300] data2;
ubyte x2 = data2.length;
auto data3 = new int[300];
ubyte x3 = data3.length;
}
It gives (dmd 2.066alpha):
test.d(5,16): Error: cannot implicitly convert expression (300u) of type uint to ubyte
test.d(7,16): Error: cannot implicitly convert expression (data3.length) of type uint to ubyte
Likewise the x2 case, this code is refused statically:
// Program #2.
void main() {
int[300] data;
foreach (ubyte i, x; data) {} // Error
}
test.d(3,5): Error: index type 'ubyte' cannot cover index range 0..300
But this code compiles and runs (and it seems to go in infinite loop):
// Program #3.
void main() {
auto data1 = new int[300];
foreach (ubyte i, x; data1) {}
int[300] data2;
foreach (ubyte i, x; data2[]) {}
}
I think accepting silently the ubyte <- size_t assignment is bad and it goes against the behavour we expect from D as shown in the x2 and x3 cases.
So I suggest to:
1) Give a warning in situations like program #3. (If you want you can also insert a run-time assert in non-release mode, that gards against the infinite loop with a clean run time error message. Perhaps Steven Schveighoffer has suggested something like this).
2) Turn the warning into a deprecation (and keep the run-time test, if already implemented).
3) Turn the deprecation into an error.
If you want you can skip the first step, and introduce a deprecation already.
See also Issue 9570
Comment #1 by pro.mathias.lang — 2020-09-02T09:46:32Z
This has been deprecated. Closing as duplicate of 9570.
*** This issue has been marked as a duplicate of issue 9570 ***