Suggestion for a D project/std module: templated format

Miles _______ at _______.____
Tue Feb 20 11:10:00 PST 2007


Since I started programming in C, I've found printf() to be wrong. The
format string, which is usually static, is parsed at run-time. GCC uses
some hints to issue warnings when you misuse printf() arguments, but
this is just to aid the inability to do this check at run-time. D have
similar issues, but at least the varargs implementation of D allows good
type-checking and argument counting at run-time.

Now, with the new mixin features of D, I think that it would be possible
to make a templated format function, that parses and does all
type-checking/argument counting at compile-time, and generates the most
efficient, perhaps inline, string formatter.

	char[] format(char[] F)(...) { ... }

User code would call it like, for example:

	format("There where %d %s, totalizing $%8.2f.")(n, plural(n, "item",
"items"), total);

It should be equivalent to calling a function exactly like:

	char[] format_XXX(int a, char[] b, real c) {
		return "There where " ~ toString(a) ~ " " ~ b
			~ ", tootalizing $" ~ ftoa(c, 8, 2) ~ ".";
	}

This means that the arguments are checked at compile-time, no string
parsing is done at run-time, and efficient "inlineable" code is
generated. Of course, l10n-aware programs would have to keep using
standard format functions, since the format strings are loaded at
run-time according to user settings.

I would love to do this, but I have severe time restrictions for the
next months while I work on an unrelated project. So I'm leaving the
idea here if someone is looking for something fun/useful to do with D,
or even a suggestion for Walter or the tango guys to add such function
template to std lib/tango.

I foresee some possible issues with argument checking, some implications
with generating function parameters from a template string argument.
Perhaps this should be possible:

	char[] gen_format_decl(char[] format) {
		...
	}

	template format(char[] F) {
		mixin(gen_format_decl(F));
	}

I leave it up to you.

Best regards,
Miles.



More information about the Digitalmars-d mailing list