Some pre-conditions at compile-time (reprise)

bearophile bearophileHUGS at lycos.com
Tue Dec 25 03:56:10 PST 2012


In the meantime the gentle Walter has answered my enhancement 
request, explaining it can't work:

http://d.puremagic.com/issues/show_bug.cgi?id=5906

Walter:

> Right now, there's a clear distinction between compile time and 
> run time
> computation. For the canonical example:
> 
>     assert(0);
> 
> We certainly do not want to run that at compile time, because 
> it's only
> supposed to fail if control flow reaches there. For compile 
> time, we've got:
> 
>     static assert(0);
> 
> which only runs at compile time.
> 
> From my POV, the "run it at compile time if possible" is fraut 
> with problems.
> There's so much in D that relies on, for example, *failing* to 
> compile an
> expression, that having a wishy-washy construct like the 
> proposal raises a big
> flag of "there be dragons".
> 
> I'm strongly opposed to this proposal.


So I have closed that ER down, waiting to open it again if and 
when there are better ideas.

I think I have to explain better what my purposes are. If I write:

void main() {
     byte x = 200;
}


The compiler refuses that code statically, it means it performs a 
compile-time test of the value:
test.d(2): Error: cannot implicitly convert expression (200) of 
type int to
byte


But if I write code like this:

void main(string[] args) {
     byte x = args.length;
}


It does not perform that test at compile-time, because it can't, 
the value is known only at run-time.


What I'm trying to archive here is a way to emulate that built-in 
behavour in user-defined types. This means if I define a MyByte 
type (that is an integral struct value with the same admissible 
values interval as a signed byte), I'd like a way to define 
MyByte contracts so this code produces a compile-time error in 
the first assignment and a run-time error in the second 
assignment (the y assignment causes a pre-condition violation at 
run-time):


void main(string[] args) {
     MyByte x = 200; // compile-time error here
     MyByte y = args.length; // run-time error here
}


(In theory it's possible to spot a bug at compile time in the 
second assignment too, but for implementation simplicity I leave 
that test to run-time.)

That's why I have suggested a "static in". But according to 
Walter answer my solution is not good enough.

Other better ideas are welcome. A solution to this problem is 
going to help D programming, making code stronger.


So how is the compiler front-end itself able to perform the range 
test only on the first assignment here? Isn't the solution used 
by the compiler generalizable in some way to user-defined types 
with pre-conditions?

void main(string[] args) {
     byte x = 200;
     byte y = args.length;
}

Bye,
bearophile


More information about the Digitalmars-d mailing list