printf() metaprogramming challenge
Jacob Carlborg
doob at me.com
Fri May 24 15:35:51 UTC 2019
On 2019-05-23 21:33, Walter Bright wrote:
> While up at night with jetlag at DConf, I started toying about solving a
> small problem. In order to use printf(), the format specifiers in the
> printf format string have to match the types of the rest of the
> parameters. This is well known to be brittle and error-prone, especially
> when refactoring the types of the arguments.
>
> (Of course, this is not a problem with writefln() and friends, but that
> isn't available in the dmd front end, nor when using betterC. Making
> printf better would mesh nicely with betterC. Note that many C compilers
> have extensions to tell you if there's a mismatch, but they won't fix it
> for you.)
>
> I thought why not use D's metaprogramming to fix it. Some ground rules:
>
> 1. No extra overhead
> 2. Completely self-contained
> 3. Only %s specifiers are rewritten
> 4. %% is handled
> 5. diagnose mismatch between number of specifiers and number of arguments
>
> Here's my solution:
>
> int i;
> dprintf!"hello %s %s %s %s betty\n"(3, 4.0, &i, "abc".ptr);
>
> gets rewritten to:
>
> printf("hello %d %g %p %s betty\n", 3, 4.0, &i, "abc".ptr);
>
This is kind of nice, but I would prefer to have a complete
implementation written in D (of sprintf) that is @nogc @safe nothrow and
pure. To avoid having to add various hacks to apply these attributes.
Would be nice if it recognizes objects and calls `toString` or `toChars`
as well.
I can also add that there was this guy at DConf that said that if a D
string should be passed to a C library it should manually pass the
pointer and length separately without any magic ;)
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list