Value ranges for slices, and more enum preconditions

bearophile via Digitalmars-d digitalmars-d at puremagic.com
Sat Jul 26 03:53:11 PDT 2014


Here D detectes a mismatch in the array lengths of a slice copy 
at compile-time (dmd 2.066beta5):


void main() {
     import std.algorithm: copy;
     int[100] a;
     int[8] b;
     const int i = 20;
     b[] = a[i .. i + 9];      // Detected at compile-time
     copy(a[i .. i + 9], b[]); // Undetected at compile-time
}


test.d(6,9): Error: mismatched array lengths, 8 and 9


In theory an "enum precondition" (if it can be implemented) 
inside the library-defined copy() could allow it to give the same 
compile-time error of the built-in operation.

To do this the compiler has to keep a kins of "value range" for 
the slice length of 'a' (and 'b'), to give such compile-time 
information to copy(), and the enum precondition of the copy() 
function needs a way to read the value ranges of both given 
slices, and assert they are equal.


Such value range analysis for slice lengths should also allow 
code like (currently refused):


void foo(int[100]) {}
void main() {
     const int[] a = new int[100];
     foo(a);
}


That is comparable to code like this (that is accepted by dmd 
2.066beta5):

void foo(ubyte z) {}
ubyte x = 100;
void main() {
     immutable int y = x;
     foo(y);
}


Bye,
bearophile


More information about the Digitalmars-d mailing list