Fear of Compiler Magic

Quirin Schroll qs.il.paperinik at gmail.com
Mon Aug 5 11:14:44 UTC 2024


On Sunday, 4 August 2024 at 17:41:52 UTC, Timon Gehr wrote:
> On 8/3/24 19:02, Walter Bright wrote:
>> On 8/2/2024 2:29 AM, Dennis wrote:
>>> You would think it's safe to transform this:
>>> ```D
>>> printf("x = %s\n", x);
>>> printf("x = %s\n", x);
>>> ```
>>>
>>> Into this:
>>> ```D
>>> const(char)* fmt = "x = %s\n";
>>> printf(fmt, x);
>>> printf(fmt, x);
>>> ```
>>>
>>> But with magic printf format string rewrites, that 
>>> transformation turns correct code into memory corrupting code 
>>> when x is an int.
>> 
>> The transformation won't compile if the call is marked @safe, 
>> and won't compile with the various proposals to increase the 
>> default safety-ness.
>> ...
>
> The simple fact is that is that the magic treatment of the 
> string-literal leads to some trouble. I.e., this is a good 
> illustration about how magic instills fear.

And it’s why I suggested using `__printf` instead. It can be an 
intrinsic (a keyword even), and be specified to require a 
compile-time constant string as its first argument, i.e. a string 
literal or something synthesized by CTFE, but nothing run-time.


More information about the Digitalmars-d mailing list