version(ctfe)

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Oct 19 06:38:56 PDT 2009


dsimcha wrote:
> This discussion originated in the T[new] thread, but I think it deserves its own
> thread.
> 
> == Quote from Denis Koroskin (2korden at gmail.com)'s article
>> An Array!(T) is really just a different name to a T[new]. You'll have the
>> same problem explaining difference between Array!(T) and T[].
>> But you are also creating a nightmare for CTFE. Since you can't use "a ~=
>> b;" anymore, you'll have to use "a = a ~ b;" which *always* allocates. Not
>> only it is syntactically less pleasant, this way you render this function
>> useless at run-time - who in the sane mind will use such an inefficient
>> stuff?
> 
> Maybe what we need is a version(ctfe) statement.  Stuff inside such a block would
> be executed only if a function is being compile time evaluated.  When code is
> generated for runtime evaluation the else block would be used.  This would allow
> problems like this to be solved in a well-encapsulated way.  Example:
> 
> uint[] findPrimes(uint maxPrime) {
>     version(ctfe) {
>         uint[] ret;
>     } else {
>         ArrayBuilder!uint ret;
>     }
> 
>     foreach(i; 0..maxPrime) {
>         if(!isPrime(i)) {
>              continue;
>         }
> 
>         version(ctfe) {
>             ret = ret ~ i;
>         } else {
>             ret ~= i;
>         }
>     }
> }
> 
> Given that CTFE will likely never support everything that is supported at runtime,
> this will likely make it much more useful.

version(ctfe) would be helpful in many other situations (e.g. 
asm-optimized routines etc.)

I thought more about it and realized that ~= can be still implemented 
for arrays if the GC cooperates.

For relatively large chunks of memory, the GC keeps a control block. We 
could add a member size_t requestedSize that keeps the size that was 
requested with an allocation/reallocation call. The GC can take 
initiative in overallocating memory and expose primitives such as 
requestedSize (how much did the program ask for?) and capacity (how much 
is really allocated?).  With that API, it is possible to implement ~= 
efficiently.


Andrei



More information about the Digitalmars-d mailing list