On Sunday, July 28, 2013, Brian Anderson wrote:
>
> I'm not a fan of printf-style format specifiers in general, largely
> because the specifiers have to be allocated in some way (fmt attribute) so
> are not particularly extensible. I can't imagine how this fmt attribute can
> be implemented in a general way using current compiler mechanisms, and am
> in favor of looking to other languages for guidance on how formatting
> should be done instead of leaning on crusty old C here.
In the "bike shedding println() and friends" thread Greydon posted a
summary of his thoughts in this area. In particular:
- format strings with nestable {n} placeholders rather than
non-nesting %-placeholders, and simple conditional forms borrowed
from the work Java and ICU/CLDR have done in this field.
I've had a brief look through these and really like the approach.
> It does seem like &Trait has a role here. I'd like to see a firm idea of
> what the runtime interface looks like. I imagine it can all be encapsulated
> in a simple signature like `fn format(&mut io::Writer, &[(&Formattable,
> FormatSpecifier)])`, where every chunk of the format string and the values
> to insert into it are cast to a stack object and paired with some metadata
> indicating how it should be formatted. Such an interface doesn't have any
> room for type-specific format traits like `Signed` though.
I was thinking along similar lines myself though in my case I had a type
signature of fn format(&mut io::Writer, &string) where string is the format
associated with the chunk. For example for the format string "the value of
x is {0:####.##}" the string passed to format would be "####.##".
Nestable format strings complicate implementation a little more. The rough
idea is:
{0:(
if count == 0 then (You have no messages.)
else (You have {count:#####} messages.)
)}
I have found format strings of this sort to be very useful in the past, in
particular for a job that involved formatting driving instructions in
30+ languages - think "At the end of the street turn left then take the
next right." In that case we used an in house XML based system. I think it
was mostly equivalent.
The formatter would need some way of getting the "count" member of 0 for
the condition and then again for formatting in the nested expression.
It would be pretty neat to evaluate all this at compile time. I think we
would have to know the specific type of each chunk. i.e. the arguments
cannot be simply of type &Trait. Perhaps a macro could be
(somehow) attached to the type being formatted and the fmt! macro could
look it up (somehow) to format the arguments.
Tricky stuff.
Thoughts?
Cheers,
Steven
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev