Invariants are useless the way they are defined

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Aug 26 14:52:25 PDT 2013


On Mon, Aug 26, 2013 at 11:47:07PM +0200, Christopher Bergqvist wrote:
[...]
> Why not have the compiler generate internal versions of all public
> methods of classes with invariants, which do not perform invariant
> checking, but contain the actual function body?
> 
> class Foo
> {
>   private int bar() const { return 5; }
>   public int baz() { return bar() * bar(); }
>   public int third() { return baz() * 2; }
>   invariant()
>   {
>     assert(bar() < 6);
>   }
> }
> 
> ..gets translated into..
> 
> class Foo
> {
>   private int bar() const { return 5; }
>   public int baz() { invariant(); int r = __internal_baz();
> invariant(); return r; }
>   private int __internal_baz() { return bar() * bar(); }
>   public int third() { invariant(); int r = __internal_third();
> invariant(); return r; }
>   private int __internal_third() { return baz() * 2; }
>   invariant()
>   {
>     assert(bar() < 6);
>   }
> }
> 
> And then in release builds simply avoid doing this generation of
> __internal_ methods, keeping the ABI (int baz() and int third()) the
> same.
> 
> A variation would be to have __internal_s call __internal_s:
>   private int __internal_third() { return __internal_baz() * 2; }
> but that diminishes ease of debugging.
> 
> Anyway, this kind of code transformation is probably impractical for
> a number of reasons. I just felt like bikeshedding.

I like this idea, actually. In fact, it did occur to me when skimming
over this thread. I don't see why this code transformation would be
impractical -- D *is* quite big on templates and compile-time code
generation, after all. :)


T

-- 
If you think you are too small to make a difference, try sleeping in a closed room with a mosquito. -- Jan van Steenbergen


More information about the Digitalmars-d mailing list