www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 12611] New: Deprecation and then error for implicit casts

https://issues.dlang.org/show_bug.cgi?id=12611

          Issue ID: 12611
           Summary: Deprecation and then error for implicit casts that
                    lose precision in foreach index loops
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Keywords: accepts-invalid
          Severity: normal
          Priority: P1
         Component: DMD
          Assignee: nobody puremagic.com
          Reporter: bearophile_hugs eml.cc

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

--
Apr 21 2014