Wanted: Format character for source code literal

Q. Schroll qs.il.paperinik at gmail.com
Mon May 3 23:08:55 UTC 2021


On Friday, 30 April 2021 at 07:10:38 UTC, Berni44 wrote:
> I plan to add an extension to `std.format`, namely a new format 
> character with the meaning of producing a source code literal. 
> Or more formally, the following snippet should work for every 
> type this extension will support:
>
> ```D
> enum a = <something>;
> enum b = mixin(format!"%S"(a));
>
> static assert(a == b && is(typeof(a) == typeof(b)));
> ```
>
> (Please note, that even for floats `a == b` should hold for all 
> values, but NaNs; I plan to use RYU for this.)
>
> The big question is now, which character to use. I thought of 
> `%S` like source code literal. Andrei suggested `%D` like D 
> literal. Both ideas have the disadvantage of using uppercase 
> letters, which would break the of uppercase letters meaning 
> that the output uses uppercase instead of lowercase (i.e. 1E10 
> instead of 1e10).
>
> A first idea of a lowercase literal might be `%l` but this 
> might easily be confused with `%I` and `%1` (both don't exist); 
> and also `l` is used in C's `printf` for `long` which we 
> luckily don't need here. Anyway I fear confusion.
>
> What do you think? Which letter would be best?

Please don't do this. Format characters can be customized. Any 
character you'd introduce for it either wouldn't work for some 
types or break those types' formatting. Why not introduce a new 
function like `dlangLiteral` that takes the value and returns a 
string? It can be used in `format` quite easily (like 
`format("pre %s post", dlangLiteral(<something>));`) and is 
explicit and not a special case at all.


More information about the Digitalmars-d mailing list