Make folly::format no longer crash on invalid format strings
[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    * Append to output.  out(StringPiece sp) may be called (more than once)
76    */
77   template <class Output>
78   void operator()(Output& out) const;
79
80   /**
81    * Append to a string.
82    */
83   template <class Str>
84   typename std::enable_if<IsSomeString<Str>::value>::type
85   appendTo(Str& str) const {
86     auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
87     (*this)(appender);
88   }
89
90   /**
91    * Conversion to string
92    */
93   std::string str() const {
94     std::string s;
95     appendTo(s);
96     return s;
97   }
98
99   /**
100    * Conversion to fbstring
101    */
102   fbstring fbstr() const {
103     fbstring s;
104     appendTo(s);
105     return s;
106   }
107
108   /**
109    * metadata to identify generated children of BaseFormatter
110    */
111   typedef detail::FormatterTag IsFormatter;
112   typedef BaseFormatter BaseType;
113
114  private:
115   typedef std::tuple<FormatValue<
116       typename std::decay<Args>::type>...> ValueTuple;
117   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
118
119   template <size_t K, class Callback>
120   typename std::enable_if<K == valueCount>::type
121   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
122     arg.error("argument index out of range, max=", i);
123   }
124
125   template <size_t K, class Callback>
126   typename std::enable_if<(K < valueCount)>::type
127   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
128     if (i == K) {
129       static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
130     } else {
131       doFormatFrom<K+1>(i, arg, cb);
132     }
133   }
134
135   template <class Callback>
136   void doFormat(size_t i, FormatArg& arg, Callback& cb) const {
137     return doFormatFrom<0>(i, arg, cb);
138   }
139
140   StringPiece str_;
141
142  protected:
143   explicit BaseFormatter(StringPiece str, Args&&... args);
144
145   // Not copyable
146   BaseFormatter(const BaseFormatter&) = delete;
147   BaseFormatter& operator=(const BaseFormatter&) = delete;
148
149   // Movable, but the move constructor and assignment operator are private,
150   // for the exclusive use of format() (below).  This way, you can't create
151   // a Formatter object, but can handle references to it (for streaming,
152   // conversion to string, etc) -- which is good, as Formatter objects are
153   // dangerous (they hold references, possibly to temporaries)
154   BaseFormatter(BaseFormatter&&) = default;
155   BaseFormatter& operator=(BaseFormatter&&) = default;
156
157   ValueTuple values_;
158 };
159
160 template <bool containerMode, class... Args>
161 class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
162                                        containerMode,
163                                        Args...> {
164  private:
165   explicit Formatter(StringPiece& str, Args&&... args)
166       : BaseFormatter<Formatter<containerMode, Args...>,
167                       containerMode,
168                       Args...>(str, std::forward<Args>(args)...) {}
169
170   template <size_t K, class Callback>
171   void doFormatArg(FormatArg& arg, Callback& cb) const {
172     std::get<K>(this->values_).format(arg, cb);
173   }
174
175   friend class BaseFormatter<Formatter<containerMode, Args...>,
176                              containerMode,
177                              Args...>;
178
179   template <class... A>
180   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
181   template <class C>
182   friend Formatter<true, C> vformat(StringPiece fmt, C&& container);
183 };
184
185 /**
186  * Formatter objects can be written to streams.
187  */
188 template<bool containerMode, class... Args>
189 std::ostream& operator<<(std::ostream& out,
190                          const Formatter<containerMode, Args...>& formatter) {
191   auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
192   formatter(writer);
193   return out;
194 }
195
196 /**
197  * Formatter objects can be written to stdio FILEs.
198  */
199 template <class Derived, bool containerMode, class... Args>
200 void writeTo(FILE* fp,
201              const BaseFormatter<Derived, containerMode, Args...>& formatter);
202
203 /**
204  * Create a formatter object.
205  *
206  * std::string formatted = format("{} {}", 23, 42).str();
207  * LOG(INFO) << format("{} {}", 23, 42);
208  * writeTo(stdout, format("{} {}", 23, 42));
209  */
210 template <class... Args>
211 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
212   return Formatter<false, Args...>(
213       fmt, std::forward<Args>(args)...);
214 }
215
216 /**
217  * Like format(), but immediately returns the formatted string instead of an
218  * intermediate format object.
219  */
220 template <class... Args>
221 inline std::string sformat(StringPiece fmt, Args&&... args) {
222   return format(fmt, std::forward<Args>(args)...).str();
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  * Like vformat(), but immediately returns the formatted string instead of an
246  * intermediate format object.
247  */
248 template <class Container>
249 inline std::string svformat(StringPiece fmt, Container&& container) {
250   return vformat(fmt, std::forward<Container>(container)).str();
251 }
252
253 /**
254  * Wrap a sequence or associative container so that out-of-range lookups
255  * return a default value rather than throwing an exception.
256  *
257  * Usage:
258  * format("[no_such_key"], defaulted(map, 42))  -> 42
259  */
260 namespace detail {
261 template <class Container, class Value> struct DefaultValueWrapper {
262   DefaultValueWrapper(const Container& container, const Value& defaultValue)
263     : container(container),
264       defaultValue(defaultValue) {
265   }
266
267   const Container& container;
268   const Value& defaultValue;
269 };
270 }  // namespace
271
272 template <class Container, class Value>
273 detail::DefaultValueWrapper<Container, Value>
274 defaulted(const Container& c, const Value& v) {
275   return detail::DefaultValueWrapper<Container, Value>(c, v);
276 }
277
278 /**
279  * Append formatted output to a string.
280  *
281  * std::string foo;
282  * format(&foo, "{} {}", 42, 23);
283  *
284  * Shortcut for toAppend(format(...), &foo);
285  */
286 template <class Str, class... Args>
287 typename std::enable_if<IsSomeString<Str>::value>::type
288 format(Str* out, StringPiece fmt, Args&&... args) {
289   format(fmt, std::forward<Args>(args)...).appendTo(*out);
290 }
291
292 /**
293  * Append vformatted output to a string.
294  */
295 template <class Str, class Container>
296 typename std::enable_if<IsSomeString<Str>::value>::type
297 vformat(Str* out, StringPiece fmt, Container&& container) {
298   vformat(fmt, std::forward<Container>(container)).appendTo(*out);
299 }
300
301 /**
302  * Utilities for all format value specializations.
303  */
304 namespace format_value {
305
306 /**
307  * Format a string in "val", obeying appropriate alignment, padding, width,
308  * and precision.  Treats Align::DEFAULT as Align::LEFT, and
309  * Align::PAD_AFTER_SIGN as Align::RIGHT; use formatNumber for
310  * number-specific formatting.
311  */
312 template <class FormatCallback>
313 void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
314
315 /**
316  * Format a number in "val"; the first prefixLen characters form the prefix
317  * (sign, "0x" base prefix, etc) which must be left-aligned if the alignment
318  * is Align::PAD_AFTER_SIGN.  Treats Align::DEFAULT as Align::LEFT.  Ignores
319  * arg.precision, as that has a different meaning for numbers (not "maximum
320  * field width")
321  */
322 template <class FormatCallback>
323 void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
324                   FormatCallback& cb);
325
326
327 /**
328  * Format a Formatter object recursively.  Behaves just like
329  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
330  * string if possible.
331  */
332 template <class FormatCallback,
333           class Derived,
334           bool containerMode,
335           class... Args>
336 void formatFormatter(
337     const BaseFormatter<Derived, containerMode, Args...>& formatter,
338     FormatArg& arg,
339     FormatCallback& cb);
340
341 }  // namespace format_value
342
343 /*
344  * Specialize folly::FormatValue for your type.
345  *
346  * FormatValue<T> is constructed with a (reference-collapsed) T&&, which is
347  * guaranteed to stay alive until the FormatValue object is destroyed, so you
348  * may keep a reference (or pointer) to it instead of making a copy.
349  *
350  * You must define
351  *   template <class Callback>
352  *   void format(FormatArg& arg, Callback& cb) const;
353  * with the following semantics: format the value using the given argument.
354  *
355  * arg is given by non-const reference for convenience -- it won't be reused,
356  * so feel free to modify it in place if necessary.  (For example, wrap an
357  * existing conversion but change the default, or remove the "key" when
358  * extracting an element from a container)
359  *
360  * Call the callback to append data to the output.  You may call the callback
361  * as many times as you'd like (or not at all, if you want to output an
362  * empty string)
363  */
364
365 namespace detail {
366
367 template <class T, class Enable = void>
368 struct IsFormatter : public std::false_type {};
369
370 template <class T>
371 struct IsFormatter<
372     T,
373     typename std::enable_if<
374         std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
375         type> : public std::true_type {};
376 } // folly::detail
377
378 // Deprecated API. formatChecked() et. al. now behave identically to their
379 // non-Checked counterparts.
380 template <class... Args>
381 Formatter<false, Args...> formatChecked(StringPiece fmt, Args&&... args) {
382   return format(fmt, std::forward<Args>(args)...);
383 }
384 template <class... Args>
385 inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
386   return formatChecked(fmt, std::forward<Args>(args)...).str();
387 }
388 template <class Container>
389 Formatter<true, Container> vformatChecked(StringPiece fmt,
390                                           Container&& container) {
391   return vformat(fmt, std::forward<Container>(container));
392 }
393 template <class Container>
394 inline std::string svformatChecked(StringPiece fmt, Container&& container) {
395   return vformatChecked(fmt, std::forward<Container>(container)).str();
396 }
397 template <class Str, class... Args>
398 typename std::enable_if<IsSomeString<Str>::value>::type
399 formatChecked(Str* out, StringPiece fmt, Args&&... args) {
400   formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
401 }
402 template <class Str, class Container>
403 typename std::enable_if<IsSomeString<Str>::value>::type
404 vformatChecked(Str* out, StringPiece fmt, Container&& container) {
405   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
406 }
407
408 }  // namespace folly
409
410 #include <folly/Format-inl.h>
411
412 #pragma GCC diagnostic pop
413
414 #endif /* FOLLY_FORMAT_H_ */