Value Preservation and Polysemy

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Nov 28 16:08:06 PST 2008


I've had a talk with Walter today, and two interesting things transpired.

First off, Walter pointed out that I was wrong about one conversion rule 
(google value preservation vs. type preservation). It turns out that 
everything that's unsigned and less than int is actually converted to 
int, NOT unsigned int as I thought. This is the case in C, C++, and D.

Second, as of today Walter devised a very crude heuristic for 
typechecking narrowing conversions:

(a) a straight assignment x = y fails if y is wider than x.

(b) however, x = e compiles for more complex expressions EVEN if there 
is potential for loss of precision.

Now enter polysemy. With that, we can get the right rules in place and 
minimize false positives. An expression will yield a polysemous value 
with the as-C-does-it type as its principal type. The secondary type is 
a carefully computed narrower type that is the tightest actual type.

If you just say auto or use the value with overloaded functions etc., 
it's just like in C - the as-in-C type will be in vigor. But if you 
specifically ask for a narrower type, the secondary type enters in effect.

Examples:

uint u1 = ...;
ushort us1 = ...;
auto a = u1 & us1; // fine, a is uint
ushort b = u1 & us1; // fine too, secondary type kicks in

long l1 = ...;
auto c = u1 / l1; // c is long
int d = u1 / l1; // fine too, secondary type kicks in

We need to think this through for complex expressions etc. Walter and I 
are quite excited that this will take care of a significant portion of 
the integral conversions mess (in addition to handling literals, 
constants, and variables within a unified framework).

The plan is to deploy polysemous integrals first without changing the 
rest of the conversion rules. At that point, if the technique turns out 
to enjoy considerable success, Walter agreed to review and possibly 
stage in the change I suggested to drop the implicit signed -> unsigned 
conversion. With that, I guess we can claim victory in the war between 
spurious vs. too lax conversions.

I'm very excited about polysemy. It's entirely original to D, covers a 
class of problems that can't be addressed with any of the known 
techniques (subtyping, coercion...) and has a kick-ass name to boot. 
Walter today mentioned he's still not sure I hadn't made "polysemy" up. 
Indeed, Thunderbird and Firefox are suggesting it's a typo - please "add 
to dictionary" :o).


Andrei



More information about the Digitalmars-d mailing list