www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - For a Safeint

reply "bearophile" <bearophileHUGS lycos.com> writes:
This post grows from the "Re: OT (partially): about promotion of 
integers" thread.

Walter:

What you (and anyone else) *can* do, today, is write a SafeInt 
struct that acts just like an int, but checks for overflow. It's 
very doable (one exists for C++). Write it, use it, and prove 
its worth. Then you'll have a far better case. Write a good one, 
and we'll consider it for Phobos.<
There are some issues to be faced (and solved) before the creation of a Safeint implemented in library D code: -------------------- 1) A Safeint (or SafeInt) should be usable in code written to use ints, unints, shorts, ubytes, and so on, as much as possible. This means I think code like this should be supported (this is a mix of D language design issue, and DMD implementation bugs): alias safeint = SafeInt!(int.min, int.max); struct Foo { safeint x; void bar() { x++; } } safeint[10] a; a[] = 1; safeint i = 5; foreach (j; 0 .. i) {} safeint z = true; safeint y; i = y = 5; safeint[] a2 = [1, 2, 3]; safeint[safeint] a3 = [1:1, 2:2, 3:3]; Another problem: http://d.puremagic.com/issues/show_bug.cgi?id=4903 Later, once safeints are implemented, some library support will be useful: safeint[10] a; safeint i = 5; writeln("%10d", a[i]); auto r = iota(i); auto s = to!string(i, 5); -------------------- 2) Safeints should be efficient, this means to access the CPU overflow flags they need to contain both asm and a fallback D implementation. But to be efficient DMD has to inline those functions in both cases. (LDC is sometimes able to inline functions that contain asm.) -------------------- 3) How do you tell the D front-end that a Safeint should support the normal algebraic simplifications supported by built-in ints? I have suggested a not enforceable attribute to tell the D compiler such user defined structs support such proprieties and simplifications. -------------------- 4) How do you perform compile-time expression range-analysis on safeInts too? So code like this doesn't compile: safeint x = long.max; // Compile-time error. alias safeubyte = SafeInt!(ubyte.min, ubyte.max); ubyte y = 50; safeubyte z = y + 230; -------------------- In the end is it harder to implement all this for a library-defined struct, or it's simpler to just add a safeint to the D language? (The library defined solution allows those improvements to be used for other future user-defined types). Bye, bearophile
Dec 11 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
In the meantime in another thread Walter has given some answers:

http://forum.dlang.org/thread/kmtckvurbknpjvczalip forum.dlang.org?page=4#post-ka8r2q:242gl5:241:40digitalmars.com

Bye,
bearophile
Dec 11 2012