On 13 May 2013 11:03, Walter Bright <newshound2@digitalmars.com> wrote:
On 5/12/2013 5:00 PM, Manu wrote:
So, here's an issue that constantly drives me nuts, and an elegant solution
seems so do-able.

It's a form of "data flow analysis". This is done by the optimizer, although it doesn't track ranges.

It isn't quite as simple as you suggest, there are issues like dealing with arbitrary control flow.


  x &= 0xFFFF;
  short s = x; // Error! (but we know x is 0 .. 65535)

Ok, but what about:

  x &= 0xFFFF;
  while (expr) {
      short s = x;
      x += 1;
  }

There's a forward reference going on. We cannot semantically evaluate s=x until we semantically evaluate the rest of the function in order to know that x is or is not reassigned.

It is done by the optimiser, but I'm suggesting that it doesn't only have value in terms of optimisation. It could improve language usability if performed in the front end.

In that context, unless the analysis is very powerful(/mature) and can statically determine 'expr', then x would need to be relaxed to unlimited at that point, since it obviously can't know the limits within (or after) that loop.
In this case, the compiler would complain that it can't determine x and you would need an explicit cast as usual.

I can see the effective forward reference issue here, which could be addressed in time, but even just reasonably simple limits tracking (ie, within sequential code) would make a massive difference. I think programmers would intuitively understand this situation and wouldn't expect magic from the compiler.
The places where it matters the most are places where it's dead obvious what the numeric limits are, and it should be equally obvious to the compiler.

It's the sort of thing that could be improved with time, but even a very simple start would be a big help in many cases.