Wanted: Format character for source code literal

Berni44 someone at somemail.com
Thu May 6 08:13:44 UTC 2021


On Wednesday, 5 May 2021 at 17:02:42 UTC, Paul Backus wrote:
> Here's the scenario that could potentially lead to trouble:
>
> 1. Some existing library uses `%D` as a custom format specifier 
> in their `toString` methods, with a meaning other than "format 
> as D source code."
>
> 2. `%D` is added to `std.format` with the meaning "format as D 
> source code," and a default implementation for types that do 
> not have custom `toString` methods.
>
> 3. A new library is written that takes advantage of (2) and 
> uses `%D` in generic code to format arbitrary values for the 
> purpose of code generation.
>
> 4. Someone uses the library from (1) and the library from (3) 
> in the same project, and library (3) ends up producing garbage, 
> because library (1)'s `%D` doesn't work the way library (3) 
> expects it to.

First of all: Thanks for clarifying. I think, I understand the 
problem now.

> The "correct" place to fix this is in library (1), but doing so 
> would require a breaking change. In practice, this means that 
> libraries like the one in (3) will never be able to completely 
> rely on the new standard for `%D`, and will always have to 
> include some kind of workaround in case they are used with 
> types like the ones in library (1).

In my opinion, the error is in (3): The new library assumes, that 
`%D` can be used with every type (and will always have the 
meaning "D literal"), which in my opinion is wrong:

It does not even hold for established characters, for example 
take `%b`: For bools, integers, characters and enums if their 
base type is one of the first three, this has currently the 
meaning "format as unsigned binary number". It currently cannot 
be used for anything else where `std.format` is responsible for.

But of course it can be used in any custom type (be it one of 
phobos or an external library or what ever). And no one will stop 
anyone from using it in a completely different way, e.g. as 
bitmap of the type or whatever.

So in my opinion in the above scenario the library in (3) should 
clearly state in its docs, that it can only be used with code 
that uses `%D` in the sense of being a "D literal". And the 
library in (1) should clearly state in its docs, what `%D` means, 
if it has a meaning. And with that it should be clear, that you 
cannot use (1) and (3) together in one project, at least not 
without adding some clue.

Now I think, I can go back to this:

>> `%D` has currently no meaning, so we cannot change it; we can 
>> just add it.
>
> `%D` *does* currently have a meaning, though. It means "custom 
> format specifier."

But doesn't that apply to *every* format specifier?


More information about the Digitalmars-d mailing list