[Issue 20101] New: BetterC: Template instantiation in CTFE only context should skip codegen / nogc / ... Phases
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Sun Aug 4 07:39:48 UTC 2019
https://issues.dlang.org/show_bug.cgi?id=20101
Issue ID: 20101
Summary: BetterC: Template instantiation in CTFE only context
should skip codegen / nogc / ... Phases
Product: D
Version: D2
Hardware: All
OS: All
Status: NEW
Severity: enhancement
Priority: P1
Component: dmd
Assignee: nobody at puremagic.com
Reporter: johannespfau at gmail.com
In D, we often uses helpers to generate code for string mixins and similar
purposes:
--------------------------------------
public string ctfeHelper()(string a)
{
return "int " ~ a ~ " = 42;";
}
extern(C) int main() @nogc
{
mixin(ctfeHelper("a"));
return a;
}
--------------------------------------
With -betterC, this code currently fails with this message:
test.d(3): Error: array concatenation of expression "int " ~ a ~ " = 42;"
requires the GC which is not available with -betterC
However, the code is exclusively used in a CTFE-only context where the GC is
conceptionally always available.
Note that if ctfeHelper was a regular function, we would have to emit runtime
code, as it is public and could be called from external code. So in that case,
the error would be correct and there's no way to make this work (except for
making ctfeHelper private, proofing that it's never used at runtime and that
it's unreachable from other modules (which is never the case, if you consider
explicitly linking to the mangled name to be valid)).
But for this example, where `ctfeHelper` is a template, we could argue that
CTFE-only instatiations should be separated from runtime instantiations: If we
do not generate code for the template in CTFE contexts, that's still perfectly
fine: Anyone calling ctfeHelper at runtime will instantiate the template again,
so the codegen can be executed there. And the user should get the errors there,
when instantiating the template in a runtime context.
Fixing this would probably involve marking an TemplateInstance as ctfeOnly.
However, it seems the implementation would be 99% identical to isSpeculative
templates. Consider this code, which already works with -betterC:
--------------------------------------
string ctfeHelper()(string a)
{
return "int " ~ a ~ " = 42;";
}
extern(C) int main() @nogc
{
return __traits(compiles, ctfeHelper("a"));
}
--------------------------------------
--
More information about the Digitalmars-d-bugs
mailing list