int to char at compile time

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Mar 20 15:30:50 PDT 2007


Hendrik Renken wrote:
> BCS wrote:
>> Reply to Hendrik,
>>
>>> i am trying something like that:
>>>
>>> char[] foo(int level, char[] msg)
>>> {
>>> static c = toString(level);

You can't make it static, since parameters aren't known when the 
function is compiled. Remember the function is also compiled for regular 
run-time use. It needs to make sense as such.
Also, std.string.toString(int) unfortunately isn't compile-time executable.

>>> return "writefln(\"%d: %s\""~ c ~", \"" ~ msg ~ "\");";
>>> }
>>> int main(char[][] args)
>>> {
>>> mixin(foo(100, "Test"));
>>> return 1;
>>> }
>>> but gdmd complaints that toString() cannot be evaluated at compile
>>> time. is there a way to convert the int to char at compile time?

Yes, see below

>> Don Clugston's decimaldigit and itoa, see 
>> http://trac.dsource.org/projects/ddl/browser/trunk/meta/conv.d

Doesn't work for CTFE parameters.

> this doesn't work for variables like "level", just with directly wrote 
> numbers.
> 
> char[] foo(int level, char[] msg)
> {
>     char[] c = itoa!(level); //does not work
>     char[] c = itoa!(100);   //does work
> }
> 
> is there no chance, to get this variable value converted?

---
import std.stdio;

char[] ctfe_itoa(int value) {
	if (value < 0) return "-" ~ ctfe_itoa(-value);
	if (value < 10) return "0123456789"[value .. value+1];
	return ctfe_itoa(value / 10) ~ ctfe_itoa(value % 10);
}

char[] foo(int level, char[] msg)
{
     auto c = ctfe_itoa(level);
     return "writefln(\"%d: %s\","~ c ~", \"" ~ msg ~ "\");";
}

int main(char[][] args)
{
    pragma(msg, foo(42u, "The answer"));
    pragma(msg, foo(int.max, "int.max"));
    mixin(foo(100, "Test"));
    return 1;
}
---

I originally wrote that function to be more efficient (so it could also 
reasonably be used at runtime) by using a stack-based buffer and 
returning buffer.dup, without any recursion. Unfortunately CTFE didn't 
like it :(.
This version will of course still work at runtime, but will perform way 
too many allocations for a function like this. (I'm not sure if this 
will be a problem at compile time).


More information about the Digitalmars-d-learn mailing list