[llvm-dev] RFC: General purpose type-safe formatting library

James Y Knight via llvm-dev llvm-dev at lists.llvm.org
Wed Oct 12 10:13:44 PDT 2016


On Tue, Oct 11, 2016 at 9:22 PM, Zachary Turner via llvm-dev <
llvm-dev at lists.llvm.org> wrote:

> A while back llvm::format() was introduced that made it possible to
> combine printf-style formatting with llvm streams.  However, this still
> comes with all the risks and pitfalls of printf.  Everyone is no-doubt
> familiar with these problems, but here are just a few anyway:
>
> 1. *Not type-safe.*  Not all compilers warn when you mess up the format
> specifier.  And when you're writing your own Printf-like functions, you
> need to tag them with __attribute__(format, printf) which again not all
> compilers have.  If you change a const char * to a StringRef, it can
> silently succeed while passing your StringRef object to printf.  It should
> fail to compile!
>
> 2. *Not security safe.  *Functions like sprintf() will happily smash your
> stack for you if you're not careful.
>
> 3. *Not portable (well kinda).  *Quick, how do you print a size_t?  You
> probably said %z.  Well MSVC didn't even support %z until 2015, which we
> aren't even officially requiring yet.  So you've gotta write (uint64_t)x
> and then use PRIx64.  Ugh.
>
> 4. *Redundant.*  If you're giving it an integer, why do you need to
> specify %d?  It's an integer!  We should be able to use the type system to
> our advantage.
>
> 5. *Not flexible.*  How do you print a std::chrono::time_point with
> llvm::format()?  You can't.  You have to resort to providing an overloaded
> streaming operator or formatting it some other way.
>
> So I've been working on a library that will solve all of these problems
> and more.
>


I wonder what use cases you envision for this? Why does LLVM need a super
extensible flexible formatting library? I mean -- if you were developing
this as a standalone project, that seems like maybe a nice feature. But I
see no rationale as to why LLVM should include it.

That is to say: wouldn't a much-simpler printf replacement, implemented
with variadic templates instead of C varargs (and which therefore doesn't
require size/signedness prefixes on %d) be sufficient for LLVM?

You can do that as a drop-in improvement for llvm::format, replacing the
call to snprintf inside the implementation with a new implementation that
actually uses the type information.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20161012/7dd4e473/attachment.html>


More information about the llvm-dev mailing list