Thread overview
CTFE in betterC needs the GC
Oct 30, 2022
arandomonlooker
Oct 30, 2022
Ali Çehreli
Oct 30, 2022
arandomonlooker
October 30, 2022

Hello, i'm a beginner to the D programming language that has posted many times for simple questions and code errors.
I have written a function that manipulates D code (passed through a q{...} block) and returns it to be compiled into the program by a mixin.
The problem is that i need to do so in -betterC mode, and for example, this code does not compile, giving an error that array concatenation of two strings at CTFE is not possible without the GC:

string exampleCTFE(string a, string b) {
    return a ~ b;
}
enum example = exampleCTFE("A", "BCDE");
int main() {
    import core.stdc.stdio;
    example.puts;
    return 0;
}

Why it complains about the GC if it's a CTFE expression that is built at compile time? There is an alternative that works in -betterC mode?
Thanks in advance.

October 29, 2022
On 10/29/22 20:41, arandomonlooker wrote:

> string exampleCTFE(string a, string b) {
>      return a ~ b;
> }

Although you need that function only at compile time, it is an ordinary function that could be called at run time as well. The function needs GC for that concatenation in the general case.

One way of solving your issue would be to change the function to a function template and pass the strings as template parameters (compile-time parameters):

string exampleCTFE(string a, string b)() {
    return a ~ b;
}

which would require explicit function template instantiation:

enum example = exampleCTFE!("A", "BCDE");

which would cause code bloat because exampleCTFE would be instantiated for every string combination that was used. For example, the following two uses would require two separate instantiations:

enum example1 = exampleCTFE!("A", "BCDE");
enum example2 = exampleCTFE!("A", "BCDEX");

> int main() {

I think you also need to specify main() as extern(C):

extern (C)
int main() {
  // ...
}

Ali

October 30, 2022
On Sunday, 30 October 2022 at 04:14:17 UTC, Ali Çehreli wrote:
> On 10/29/22 20:41, arandomonlooker wrote:
>
> > [...]
>
> Although you need that function only at compile time, it is an ordinary function that could be called at run time as well. The function needs GC for that concatenation in the general case.
>
> [...]

Thank you, Ali.