Suggested Change to Contract Syntax

Xinok via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 10 14:04:24 PST 2016


On Thursday, 10 March 2016 at 21:07:09 UTC, FatalCatharsis wrote:
> I am very new to D so I apologize if I'm very uninformed. I'm 
> learning D by porting a big (awful) c++ project to D so that I 
> may take advantage of all the lovely testing and QA features. I 
> am currently moving a class over that I have which represents a 
> 2 float vector and I've run into a problem with contracts. Here 
> is a short excerpt:
> ...

The most "elegant" solution I can think of is to move the 
contracts into the body of the function itself and wrap them in 
version(unittest) or version(assert). The pre-contract would be 
placed at the very start of the function and the post-contract 
would be wrapped in a scope(exit) or scope(success).

Regarding your proposal, I don't think it's necessary to 
introduce new syntax; a simple change in semantics would suffice. 
If we simply preserved the body of the pre-contract and made it 
accessible in the post-contract, then your example would work as 
is.

I'm not sure how the compilers translate the contracts into code, 
but it's definitely feasible. Code of the form:

     auto foo()
     in{ ... }
     out(result){ ... }
     body{ ... }

Could simply be rewritten as:

     auto foo()
     {
         // paste pre-contract here

         auto bodyOfFoo()
         {
             // paste body here
         }

         auto result = bodyOfFoo();

         // paste post-contract here

         return result;
     }


More information about the Digitalmars-d mailing list