www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Value ranges for slices, and more enum preconditions

reply "bearophile" <bearophileHUGS lycos.com> writes:
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
Jul 26 2014
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
After thinking a bit more about this topic I have opened an ER, 
because I think this could statically catch some slice-related 
bugs and allow some safe implicit casts:

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

Just a curiosity of mine: Do you remember who originally proposed 
to add the value range analysis to D (and the link to the 
posts/discussion)?

Bye,
bearophile
Jul 30 2014
parent Andrei Alexandrescu <SeeWebsiteForEmail erdani.org> writes:
On 7/30/14, 11:51 AM, bearophile wrote:
 Just a curiosity of mine: Do you remember who originally proposed to add
 the value range analysis to D (and the link to the posts/discussion)?
It was conceived by Walter, Brad, Bartosz Milewski, Eric Niebler, and myself during one of our infamous weekend meetings in Seattle. I vaguely recall Brad was the first to mention it or at least point out the connection with the compiler optimization. -- Andrei
Jul 30 2014