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