Robert Jacques wrote:
On Tue, 07 Jul 2009 11:36:26 -0400, Andrei Alexandrescu <[email protected]> wrote:
Robert Jacques wrote:
Andrei, I have a short vector template (think vec!(byte,3), etc) where I've had to wrap the majority lines of code in cast(T)( ... ), because I support bytes and shorts. I find that both a kludge and a pain.

Well suggestions for improving things are welcome. But I don't think it will fly to make int+int yield a long.

Suggestion 1:
Loft the right hand of the expression (when lofting is valid) to the size of the left hand. i.e.

What does loft mean in this context?

byte a,b,c;
c = a + b;  => c = a + b;

Unsafe.

short d;
d = a + b;  => d = cast(short) a + cast(short) b;

Should work today modulo bugs.

int e, f;
e = a + b;  => e = cast(short) a + cast(short) b;

Why cast to short? e has type int.

e = a + b + d; => e = cast(int)(cast(short) a + cast(short) b) + cast(int) d; Or e = cast(int) a + (cast(int) b + cast(int)d);

I don't understand this.

long g;
g = e + f;  => d = cast(long) e + cast(long) f;

Works today.

When choosing operator overloads or auto, prefer the ideal lofted interpretation (as per the new rules, but without the exception for int/long), over truncated variants. i.e.
auto h = a + b; => short h = cast(short) a + cast(short) b;

This would yield semantics incompatible with C expressions.

This would also properly handled some of the corner/inconsistent cases with the current rules:
ubyte  i;
ushort j;
j = -i; => j = -cast(short)i; (This currently evaluates to j = cast(short)(-i);

That should not compile, sigh. Walter wouldn't listen...

And
a += a;
is equivalent to
a = a + a;

Well not quite equivalent. In D2 they aren't. The former clarifies that you want to reassign the expression to a, and no cast is necessary. The latter would not compile if a is shorter than int.

and is logically consistent with
byte[] k,l,m;
m[] = k[] + l[];

Essentially, instead of trying to prevent overflows, except for those from int and long, this scheme attempts to minimize the risk of overflows, including those from int (and long, once cent exists. Maybe long+long=>bigInt?)

But if you close operations for types smaller than int, you end up with a scheme even more error-prone that C!

Suggestion 2:
Enable the full rules as part of SafeD and allow non-promotion in un-safe D. Note this could be synergistically combined with Suggestion 1.

Safe D is concerned with memory safety only.


Andrei

Reply via email to