pragma(__ctfe)

Dave P. dave287091 at gmail.com
Thu Sep 28 19:56:25 UTC 2023


On Thursday, 28 September 2023 at 17:04:00 UTC, Steven 
Schveighoffer wrote:
> On 9/27/23 11:30 PM, Nicholas Wilson wrote:
>> I have need of the ability to suppress the code generation of 
>> functions for using mixin generation functions with dcompute. 
>> Below is a link to a PR to implement that functionality.
>> 
>> https://github.com/dlang/dmd/pull/15636
>> 
>> What are peoples thoughts on this?
>
> Have you tried immediately-called lambdas?
>
> What I need is for this to work:
>
> ```d
> void foo() @nogc
> {
>    int[] buf;
>    if (__ctfe) {
>       buf = new int[10000];
>    }
>    else {
>       buf = (cast(int*)malloc(int.sizeof * 10000))[0 .. 10000];
>    }
>    scope(exit) if(!__ctfe) free(buf.ptr);
>    ... // use buf
> }
> ```
>
> We need the compiler to back-off when it comes to enforcing 
> runtime attributes in compile-time-only blocks. Without it, 
> reasonable backup plans don't exist for what seems like obvious 
> allowances. BetterC CTFE code becomes impossible, etc.
>
> I'd also like to see `assert(__ctfe)` just suppress code 
> generation, as mentioned.
>
> -Steve

As far as I can tell, this already works.

```d
import core.stdc.stdlib;
import core.stdc.stdio;
int foo() @nogc
{
    int[] buf;
    if (__ctfe) {
       buf = new int[10000];
    }
    else {
       buf = (cast(int*)malloc(int.sizeof * 10000))[0 .. 10000];
    }
    scope(exit) if(!__ctfe) free(buf.ptr);
    foreach(ref b; buf){
        b = 2;
    }
    int x = 0;
    foreach(b; buf){
        x += b;
    }
    return x;
}

enum z = foo();
pragma(msg, z);


void d_main(){
     int y = foo();
     printf("%d\n", y);
     printf("%d\n", z);
}

version(D_BetterC){
     extern(C)
     int main(){
         d_main();
         return 0;
     }
}
else {
     void main(){
         d_main();
     }
}
```

works with betterC, normal D, works at compile time, runtime.


It works as this bug was resolved: 
https://issues.dlang.org/show_bug.cgi?id=21492


More information about the Digitalmars-d mailing list