Add defaulted() in Format.h to avoid throwing on missing keys; add string-y dynamic...
[folly.git] / folly / Format.h
1 /*
2  * Copyright 2014 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 /**
55  * Formatter class.
56  *
57  * Note that this class is tricky, as it keeps *references* to its arguments
58  * (and doesn't copy the passed-in format string).  Thankfully, you can't use
59  * this directly, you have to use format(...) below.
60  */
61
62 template <bool containerMode, class... Args>
63 class Formatter {
64  public:
65   /*
66    * Change whether or not Formatter should crash or throw exceptions if the
67    * format string is invalid.
68    *
69    * Crashing is desirable for literal format strings that are fixed at compile
70    * time.  Errors in the format string are generally programmer bugs, and
71    * should be caught early on in development.  Crashing helps ensure these
72    * problems are noticed.
73    */
74   void setCrashOnError(bool crash) {
75     crashOnError_ = crash;
76   }
77
78   /**
79    * Append to output.  out(StringPiece sp) may be called (more than once)
80    */
81   template <class Output>
82   void operator()(Output& out) const;
83
84   /**
85    * Append to a string.
86    */
87   template <class Str>
88   typename std::enable_if<IsSomeString<Str>::value>::type
89   appendTo(Str& str) const {
90     auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
91     (*this)(appender);
92   }
93
94   /**
95    * Conversion to string
96    */
97   std::string str() const {
98     std::string s;
99     appendTo(s);
100     return s;
101   }
102
103   /**
104    * Conversion to fbstring
105    */
106   fbstring fbstr() const {
107     fbstring s;
108     appendTo(s);
109     return s;
110   }
111
112  private:
113   explicit Formatter(StringPiece str, Args&&... args);
114
115   // Not copyable
116   Formatter(const Formatter&) = delete;
117   Formatter& operator=(const Formatter&) = delete;
118
119   // Movable, but the move constructor and assignment operator are private,
120   // for the exclusive use of format() (below).  This way, you can't create
121   // a Formatter object, but can handle references to it (for streaming,
122   // conversion to string, etc) -- which is good, as Formatter objects are
123   // dangerous (they hold references, possibly to temporaries)
124   Formatter(Formatter&&) = default;
125   Formatter& operator=(Formatter&&) = default;
126
127   typedef std::tuple<FormatValue<
128       typename std::decay<Args>::type>...> ValueTuple;
129   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
130
131   FOLLY_NORETURN void handleFormatStrError() const;
132   template <class Output>
133   void appendOutput(Output& out) const;
134
135   template <size_t K, class Callback>
136   typename std::enable_if<K == valueCount>::type
137   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
138     arg.error("argument index out of range, max=", i);
139   }
140
141   template <size_t K, class Callback>
142   typename std::enable_if<(K < valueCount)>::type
143   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
144     if (i == K) {
145       std::get<K>(values_).format(arg, cb);
146     } else {
147       doFormatFrom<K+1>(i, arg, cb);
148     }
149   }
150
151   template <class Callback>
152   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
153     return doFormatFrom<0>(i, arg, cb);
154   }
155
156   StringPiece str_;
157   ValueTuple values_;
158   bool crashOnError_{true};
159
160   template <class... A>
161   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
162   template <class... A>
163   friend Formatter<false, A...> formatChecked(StringPiece fmt, A&&... arg);
164   template <class C>
165   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
166   template <class C>
167   friend Formatter<true, C> vformatChecked(StringPiece fmt, C&& container);
168 };
169
170 /**
171  * Formatter objects can be written to streams.
172  */
173 template<bool containerMode, class... Args>
174 std::ostream& operator<<(std::ostream& out,
175                          const Formatter<containerMode, Args...>& formatter) {
176   auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
177   formatter(writer);
178   return out;
179 }
180
181 /**
182  * Formatter objects can be written to stdio FILEs.
183  */
184 template<bool containerMode, class... Args>
185 void writeTo(FILE* fp, const Formatter<containerMode, Args...>& formatter);
186
187 /**
188  * Create a formatter object.
189  *
190  * std::string formatted = format("{} {}", 23, 42).str();
191  * LOG(INFO) << format("{} {}", 23, 42);
192  * writeTo(stdout, format("{} {}", 23, 42));
193  *
194  * Note that format() will crash the program if the format string is invalid.
195  * Normally, the format string is a fixed string literal specified by the
196  * programmer.  Invalid format strings are normally programmer bugs, and should
197  * be caught early on during development.  Crashing helps ensure these bugs are
198  * found.
199  *
200  * Use formatChecked() if you have a dynamic format string (for example, a user
201  * supplied value).  formatChecked() will throw an exception rather than
202  * crashing the program.
203  */
204 template <class... Args>
205 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
206   return Formatter<false, Args...>(
207       fmt, std::forward<Args>(args)...);
208 }
209
210 /**
211  * Create a formatter object from a dynamic format string.
212  *
213  * This is identical to format(), but throws an exception if the format string
214  * is invalid, rather than aborting the program.  This allows it to be used
215  * with user-specified format strings which are not guaranteed to be well
216  * formed.
217  */
218 template <class... Args>
219 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
220   Formatter<false, Args...> f(fmt, std::forward<Args>(args)...);
221   f.setCrashOnError(false);
222   return f;
223 }
224
225 /**
226  * Create a formatter object that takes one argument (of container type)
227  * and uses that container to get argument values from.
228  *
229  * std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };
230  *
231  * The following are equivalent:
232  * format("{0[hello]} {0[answer]}", map);
233  *
234  * vformat("{hello} {answer}", map);
235  *
236  * but the latter is cleaner.
237  */
238 template <class Container>
239 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
240   return Formatter<true, Container>(
241       fmt, std::forward<Container>(container));
242 }
243
244 /**
245  * Create a formatter object from a dynamic format string.
246  *
247  * This is identical to vformat(), but throws an exception if the format string
248  * is invalid, rather than aborting the program.  This allows it to be used
249  * with user-specified format strings which are not guaranteed to be well
250  * formed.
251  */
252 template <class Container>
253 Formatter<true, Container> vformatChecked(StringPiece fmt,
254                                           Container&& container) {
255   Formatter<true, Container> f(fmt, std::forward<Container>(container));
256   f.setCrashOnError(false);
257   return f;
258 }
259
260 /**
261  * Wrap a sequence or associative container so that out-of-range lookups
262  * return a default value rather than throwing an exception.
263  *
264  * Usage:
265  * format("[no_such_key"], defaulted(map, 42))  -> 42
266  */
267 namespace detail {
268 template <class Container, class Value> struct DefaultValueWrapper {
269   DefaultValueWrapper(const Container& container, const Value& defaultValue)
270     : container(container),
271       defaultValue(defaultValue) {
272   }
273
274   const Container& container;
275   const Value& defaultValue;
276 };
277 }  // namespace
278
279 template <class Container, class Value>
280 detail::DefaultValueWrapper<Container, Value>
281 defaulted(const Container& c, const Value& v) {
282   return detail::DefaultValueWrapper<Container, Value>(c, v);
283 }
284
285 /**
286  * Append formatted output to a string.
287  *
288  * std::string foo;
289  * format(&foo, "{} {}", 42, 23);
290  *
291  * Shortcut for toAppend(format(...), &foo);
292  */
293 template <class Str, class... Args>
294 typename std::enable_if<IsSomeString<Str>::value>::type
295 format(Str* out, StringPiece fmt, Args&&... args) {
296   format(fmt, std::forward<Args>(args)...).appendTo(*out);
297 }
298
299 template <class Str, class... Args>
300 typename std::enable_if<IsSomeString<Str>::value>::type
301 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
302   formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
303 }
304
305 /**
306  * Append vformatted output to a string.
307  */
308 template <class Str, class Container>
309 typename std::enable_if<IsSomeString<Str>::value>::type
310 vformat(Str* out, StringPiece fmt, Container&& container) {
311   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
312 }
313
314 template <class Str, class Container>
315 typename std::enable_if<IsSomeString<Str>::value>::type
316 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
317   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
318 }
319
320 /**
321  * Utilities for all format value specializations.
322  */
323 namespace format_value {
324
325 /**
326  * Format a string in "val", obeying appropriate alignment, padding, width,
327  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
328  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
329  * number-specific formatting.
330  */
331 template <class FormatCallback>
332 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
333
334 /**
335  * Format a number in "val"; the first prefixLen characters form the prefix
336  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
337  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
338  * arg.precision, as that has a different meaning for numbers (not "maximum
339  * field width")
340  */
341 template <class FormatCallback>
342 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
343                   FormatCallback& cb);
344
345
346 /**
347  * Format a Formatter object recursively.  Behaves just like
348  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
349  * string if possible.
350  */
351 template <class FormatCallback, bool containerMode, class... Args>
352 void formatFormatter(const Formatter<containerMode, Args...>& formatter,
353                      FormatArg& arg,
354                      FormatCallback& cb);
355
356 }  // namespace format_value
357
358 /*
359  * Specialize folly::FormatValue for your type.
360  *
361  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
362  * guaranteed to stay alive until the FormatValue object is destroyed, so you
363  * may keep a reference (or pointer) to it instead of making a copy.
364  *
365  * You must define
366  *   template <class Callback>
367  *   void format(FormatArg& arg, Callback& cb) const;
368  * with the following semantics: format the value using the given argument.
369  *
370  * arg is given by non-const reference for convenience -- it won't be reused,
371  * so feel free to modify it in place if necessary.  (For example, wrap an
372  * existing conversion but change the default, or remove the "key" when
373  * extracting an element from a container)
374  *
375  * Call the callback to append data to the output.  You may call the callback
376  * as many times as you'd like (or not at all, if you want to output an
377  * empty string)
378  */
379
380 }  // namespace folly
381
382 #include "folly/Format-inl.h"
383
384 #pragma GCC diagnostic pop
385
386 #endif /* FOLLY_FORMAT_H_ */