More value range analysis?

bearophile bearophileHUGS at lycos.com
Thu Jan 3 19:09:37 PST 2013


I think the value range analysis was designed to be limited to 
single expressions to keep it simple to implement, fast to run to 
keep compilation time low, and to avoid flow analysis. But with 
immutability there is much less need for flow analysis.

So maybe it's possible to introduce in D value range analysis 
across different expressions if those expressions are immutable. 
A simple example:


void main(string[] args) {
     ubyte x = cast(ubyte)args.length;
     immutable int y = x;
     // Here y must be in [0, 256[.
}



Two other useful cases:


void main() {
     foreach (immutable i; 0 .. 256) {
         // Here i is in [0, 10[.
         ubyte x = i; // No need for a cast here.
     }

     int[10] a;
     foreach (immutable i; 0 .. a.length) {
         // Here i is in [0, a.length[,
         // this is useful if a.length is immutable.
         a[i] = 5; // No array bound tests here.
     }
}



In D there are situations where immutability is not enough; a 
simple option is just to ignore such cases (this means in such 
cases the value range analysis will not work across different 
expressions, and this code will keep generating four error 
messages):


immutable uint x;
immutable ubyte y;
static this() {
     x = 255;
     y = x;
     x++;
     y = x;
}
class Foo {
     immutable uint a;
     immutable ubyte b;
     this() {
         a = 255;
         b = a;
         a++;
         b = a;
     }
}
void main() {}


Bye,
bearophile


More information about the Digitalmars-d mailing list