Copyright 2014->2015
[folly.git] / folly / Format.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_FORMAT_H_
18 #define FOLLY_FORMAT_H_
19
20 #include <array>
21 #include <cstdio>
22 #include <tuple>
23 #include <type_traits>
24 #include <vector>
25 #include <deque>
26 #include <map>
27 #include <unordered_map>
28
29 #include <double-conversion/double-conversion.h>
30
31 #include <folly/FBVector.h>
32 #include <folly/Conv.h>
33 #include <folly/Range.h>
34 #include <folly/Traits.h>
35 #include <folly/Likely.h>
36 #include <folly/String.h>
37 #include <folly/small_vector.h>
38 #include <folly/FormatArg.h>
39
40 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
41 #pragma GCC diagnostic push
42 #pragma GCC diagnostic ignored "-Wshadow"
43
44 namespace folly {
45
46 // forward declarations
47 template <bool containerMode, class... Args> class Formatter;
48 template <class... Args>
49 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
50 template <class C>
51 Formatter<true, C> vformat(StringPiece fmt, C&& container);
52 template <class T, class Enable=void> class FormatValue;
53
54 // meta-attribute to identify formatters in this sea of template weirdness
55 namespace detail {
56 class FormatterTag {};
57 };
58
59 /**
60  * Formatter class.
61  *
62  * Note that this class is tricky, as it keeps *references* to its arguments
63  * (and doesn't copy the passed-in format string).  Thankfully, you can't use
64  * this directly, you have to use format(...) below.
65  */
66
67 /* BaseFormatter class. Currently, the only behavior that can be
68  * overridden is the actual formatting of positional parameters in
69  * `doFormatArg`. The Formatter class provides the default implementation.
70  */
71 template <class Derived, bool containerMode, class... Args>
72 class BaseFormatter {
73  public:
74   /*
75    * Change whether or not Formatter should crash or throw exceptions if the
76    * format string is invalid.
77    *
78    * Crashing is desirable for literal format strings that are fixed at compile
79    * time.  Errors in the format string are generally programmer bugs, and
80    * should be caught early on in development.  Crashing helps ensure these
81    * problems are noticed.
82    */
83   void setCrashOnError(bool crash) {
84     crashOnError_ = crash;
85   }
86
87   /**
88    * Append to output.  out(StringPiece sp) may be called (more than once)
89    */
90   template <class Output>
91   void operator()(Output& out) const;
92
93   /**
94    * Append to a string.
95    */
96   template <class Str>
97   typename std::enable_if<IsSomeString<Str>::value>::type
98   appendTo(Str& str) const {
99     auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
100     (*this)(appender);
101   }
102
103   /**
104    * Conversion to string
105    */
106   std::string str() const {
107     std::string s;
108     appendTo(s);
109     return s;
110   }
111
112   /**
113    * Conversion to fbstring
114    */
115   fbstring fbstr() const {
116     fbstring s;
117     appendTo(s);
118     return s;
119   }
120
121   /**
122    * metadata to identify generated children of BaseFormatter
123    */
124   typedef detail::FormatterTag IsFormatter;
125   typedef BaseFormatter BaseType;
126
127  private:
128   typedef std::tuple<FormatValue<
129       typename std::decay<Args>::type>...> ValueTuple;
130   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
131
132   FOLLY_NORETURN void handleFormatStrError() const;
133   template <class Output>
134   void appendOutput(Output& out) const;
135
136   template <size_t K, class Callback>
137   typename std::enable_if<K == valueCount>::type
138   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
139     arg.error("argument index out of range, max=", i);
140   }
141
142   template <size_t K, class Callback>
143   typename std::enable_if<(K < valueCount)>::type
144   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
145     if (i == K) {
146       static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
147     } else {
148       doFormatFrom<K+1>(i, arg, cb);
149     }
150   }
151
152   template <class Callback>
153   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
154     return doFormatFrom<0>(i, arg, cb);
155   }
156
157   StringPiece str_;
158   bool crashOnError_{true};
159
160  protected:
161   explicit BaseFormatter(StringPiece str, Args&&... args);
162
163   // Not copyable
164   BaseFormatter(const BaseFormatter&) = delete;
165   BaseFormatter& operator=(const BaseFormatter&) = delete;
166
167   // Movable, but the move constructor and assignment operator are private,
168   // for the exclusive use of format() (below).  This way, you can't create
169   // a Formatter object, but can handle references to it (for streaming,
170   // conversion to string, etc) -- which is good, as Formatter objects are
171   // dangerous (they hold references, possibly to temporaries)
172   BaseFormatter(BaseFormatter&&) = default;
173   BaseFormatter& operator=(BaseFormatter&&) = default;
174
175   ValueTuple values_;
176 };
177
178 template <bool containerMode, class... Args>
179 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
180                                        containerMode,
181                                        Args...> {
182  private:
183   explicit Formatter(StringPiece& str, Args&&... args)
184       : BaseFormatter<Formatter<containerMode, Args...>,
185                       containerMode,
186                       Args...>(str, std::forward<Args>(args)...) {}
187
188   template <size_t K, class Callback>
189   void doFormatArg(FormatArg& arg, Callback& cb) const {
190     std::get<K>(this->values_).format(arg, cb);
191   }
192
193   friend class BaseFormatter<Formatter<containerMode, Args...>,
194                              containerMode,
195                              Args...>;
196
197   template <class... A>
198   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
199   template <class... A>
200   friend Formatter<false, A...> formatChecked(StringPiece fmt, A&&... arg);
201   template <class C>
202   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
203   template <class C>
204   friend Formatter<true, C> vformatChecked(StringPiece fmt, C&& container);
205 };
206
207 /**
208  * Formatter objects can be written to streams.
209  */
210 template<bool containerMode, class... Args>
211 std::ostream& operator<<(std::ostream& out,
212                          const Formatter<containerMode, Args...>& formatter) {
213   auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
214   formatter(writer);
215   return out;
216 }
217
218 /**
219  * Formatter objects can be written to stdio FILEs.
220  */
221 template <class Derived, bool containerMode, class... Args>
222 void writeTo(FILE* fp,
223              const BaseFormatter<Derived, containerMode, Args...>& formatter);
224
225 /**
226  * Create a formatter object.
227  *
228  * std::string formatted = format("{} {}", 23, 42).str();
229  * LOG(INFO) << format("{} {}", 23, 42);
230  * writeTo(stdout, format("{} {}", 23, 42));
231  *
232  * Note that format() will crash the program if the format string is invalid.
233  * Normally, the format string is a fixed string literal specified by the
234  * programmer.  Invalid format strings are normally programmer bugs, and should
235  * be caught early on during development.  Crashing helps ensure these bugs are
236  * found.
237  *
238  * Use formatChecked() if you have a dynamic format string (for example, a user
239  * supplied value).  formatChecked() will throw an exception rather than
240  * crashing the program.
241  */
242 template <class... Args>
243 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
244   return Formatter<false, Args...>(
245       fmt, std::forward<Args>(args)...);
246 }
247
248 /**
249  * Like format(), but immediately returns the formatted string instead of an
250  * intermediate format object.
251  */
252 template <class... Args>
253 inline std::string sformat(StringPiece fmt, Args&&... args) {
254   return format(fmt, std::forward<Args>(args)...).str();
255 }
256
257 /**
258  * Create a formatter object from a dynamic format string.
259  *
260  * This is identical to format(), but throws an exception if the format string
261  * is invalid, rather than aborting the program.  This allows it to be used
262  * with user-specified format strings which are not guaranteed to be well
263  * formed.
264  */
265 template <class... Args>
266 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
267   Formatter<false, Args...> f(fmt, std::forward<Args>(args)...);
268   f.setCrashOnError(false);
269   return f;
270 }
271
272 /**
273  * Like formatChecked(), but immediately returns the formatted string instead of
274  * an intermediate format object.
275  */
276 template <class... Args>
277 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
278   return formatChecked(fmt, std::forward<Args>(args)...).str();
279 }
280
281 /**
282  * Create a formatter object that takes one argument (of container type)
283  * and uses that container to get argument values from.
284  *
285  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
286  *
287  * The following are equivalent:
288  * format("{0[hello]} {0[answer]}", map);
289  *
290  * vformat("{hello} {answer}", map);
291  *
292  * but the latter is cleaner.
293  */
294 template <class Container>
295 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
296   return Formatter<true, Container>(
297       fmt, std::forward<Container>(container));
298 }
299
300 /**
301  * Like vformat(), but immediately returns the formatted string instead of an
302  * intermediate format object.
303  */
304 template <class Container>
305 inline std::string svformat(StringPiece fmt, Container&& container) {
306   return vformat(fmt, std::forward<Container>(container)).str();
307 }
308
309 /**
310  * Create a formatter object from a dynamic format string.
311  *
312  * This is identical to vformat(), but throws an exception if the format string
313  * is invalid, rather than aborting the program.  This allows it to be used
314  * with user-specified format strings which are not guaranteed to be well
315  * formed.
316  */
317 template <class Container>
318 Formatter<true, Container> vformatChecked(StringPiece fmt,
319                                           Container&& container) {
320   Formatter<true, Container> f(fmt, std::forward<Container>(container));
321   f.setCrashOnError(false);
322   return f;
323 }
324
325 /**
326  * Like vformatChecked(), but immediately returns the formatted string instead
327  * of an intermediate format object.
328  */
329 template <class Container>
330 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
331   return vformatChecked(fmt, std::forward<Container>(container)).str();
332 }
333
334 /**
335  * Wrap a sequence or associative container so that out-of-range lookups
336  * return a default value rather than throwing an exception.
337  *
338  * Usage:
339  * format("[no_such_key"], defaulted(map, 42))  -> 42
340  */
341 namespace detail {
342 template <class Container, class Value> struct DefaultValueWrapper {
343   DefaultValueWrapper(const Container& container, const Value& defaultValue)
344     : container(container),
345       defaultValue(defaultValue) {
346   }
347
348   const Container& container;
349   const Value& defaultValue;
350 };
351 }  // namespace
352
353 template <class Container, class Value>
354 detail::DefaultValueWrapper<Container, Value>
355 defaulted(const Container& c, const Value& v) {
356   return detail::DefaultValueWrapper<Container, Value>(c, v);
357 }
358
359 /**
360  * Append formatted output to a string.
361  *
362  * std::string foo;
363  * format(&foo, "{} {}", 42, 23);
364  *
365  * Shortcut for toAppend(format(...), &foo);
366  */
367 template <class Str, class... Args>
368 typename std::enable_if<IsSomeString<Str>::value>::type
369 format(Str* out, StringPiece fmt, Args&&... args) {
370   format(fmt, std::forward<Args>(args)...).appendTo(*out);
371 }
372
373 template <class Str, class... Args>
374 typename std::enable_if<IsSomeString<Str>::value>::type
375 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
376   formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
377 }
378
379 /**
380  * Append vformatted output to a string.
381  */
382 template <class Str, class Container>
383 typename std::enable_if<IsSomeString<Str>::value>::type
384 vformat(Str* out, StringPiece fmt, Container&& container) {
385   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
386 }
387
388 template <class Str, class Container>
389 typename std::enable_if<IsSomeString<Str>::value>::type
390 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
391   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
392 }
393
394 /**
395  * Utilities for all format value specializations.
396  */
397 namespace format_value {
398
399 /**
400  * Format a string in "val", obeying appropriate alignment, padding, width,
401  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
402  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
403  * number-specific formatting.
404  */
405 template <class FormatCallback>
406 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
407
408 /**
409  * Format a number in "val"; the first prefixLen characters form the prefix
410  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
411  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
412  * arg.precision, as that has a different meaning for numbers (not "maximum
413  * field width")
414  */
415 template <class FormatCallback>
416 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
417                   FormatCallback& cb);
418
419
420 /**
421  * Format a Formatter object recursively.  Behaves just like
422  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
423  * string if possible.
424  */
425 template <class FormatCallback,
426           class Derived,
427           bool containerMode,
428           class... Args>
429 void formatFormatter(
430     const BaseFormatter<Derived, containerMode, Args...>& formatter,
431     FormatArg& arg,
432     FormatCallback& cb);
433
434 }  // namespace format_value
435
436 /*
437  * Specialize folly::FormatValue for your type.
438  *
439  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
440  * guaranteed to stay alive until the FormatValue object is destroyed, so you
441  * may keep a reference (or pointer) to it instead of making a copy.
442  *
443  * You must define
444  *   template <class Callback>
445  *   void format(FormatArg& arg, Callback& cb) const;
446  * with the following semantics: format the value using the given argument.
447  *
448  * arg is given by non-const reference for convenience -- it won't be reused,
449  * so feel free to modify it in place if necessary.  (For example, wrap an
450  * existing conversion but change the default, or remove the "key" when
451  * extracting an element from a container)
452  *
453  * Call the callback to append data to the output.  You may call the callback
454  * as many times as you'd like (or not at all, if you want to output an
455  * empty string)
456  */
457
458 namespace detail {
459
460 template <class T, class Enable = void>
461 struct IsFormatter : public std::false_type {};
462
463 template <class T>
464 struct IsFormatter<
465     T,
466     typename std::enable_if<
467         std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
468         type> : public std::true_type {};
469 } // folly::detail
470
471 }  // namespace folly
472
473 #include <folly/Format-inl.h>
474
475 #pragma GCC diagnostic pop
476
477 #endif /* FOLLY_FORMAT_H_ */