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