Some pre-conditions at compile-time (reprise)

Artur Skawina art.08.09 at gmail.com
Tue Dec 25 05:44:11 PST 2012


On 12/25/12 12:56, bearophile wrote:
> 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". 


http://forum.dlang.org/thread/kmpcxvrvhjeomitpfnri@forum.dlang.org#post-mailman.1091.1344265074.31962.digitalmars-d-learn:40puremagic.com

You'd just need an ctor/opAssign overload that would deal with the known-values case.
Ditto for other ops. But there are so many other D problems that worrying about
things like this doesn't make any sense right now. Also, it's the cases like

   MyByte x = 100, y = 20;
   MyByte z = x+y;

that need to work (ie have zero RT overhead), and handling them is a little trickier.
But likely doable, by using separate "MyByte" types that know their true ranges.
Except, then the above syntax won't work anymore, so you'd need additional language
changes. Which would be a good idea anyway; but shouldn't be a priority now.

artur


More information about the Digitalmars-d mailing list