logging: rename the `DEBUG` log level to `DBG`
[folly.git] / folly / Format.h
index e3134a33339df78345c65b4543630b5926fd3472..2c5f2fc3c32342f931f82339bb173c15c21621b1 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015 Facebook, Inc.
+ * Copyright 2012-present Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * limitations under the License.
  */
 
-#ifndef FOLLY_FORMAT_H_
+#pragma once
 #define FOLLY_FORMAT_H_
 
 #include <cstdio>
+#include <stdexcept>
 #include <tuple>
 #include <type_traits>
 
+#include <folly/CPortability.h>
 #include <folly/Conv.h>
+#include <folly/FormatArg.h>
 #include <folly/Range.h>
-#include <folly/Traits.h>
 #include <folly/String.h>
-#include <folly/FormatArg.h>
+#include <folly/Traits.h>
 
 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wshadow"
+FOLLY_PUSH_WARNING
+FOLLY_GCC_DISABLE_WARNING("-Wshadow")
 
 namespace folly {
 
 // forward declarations
-template <bool containerMode, class... Args> class Formatter;
+template <bool containerMode, class... Args>
+class Formatter;
 template <class... Args>
 Formatter<false, Args...> format(StringPiece fmt, Args&&... args);
 template <class C>
 Formatter<true, C> vformat(StringPiece fmt, C&& container);
-template <class T, class Enable=void> class FormatValue;
+template <class T, class Enable = void>
+class FormatValue;
 
 // meta-attribute to identify formatters in this sea of template weirdness
 namespace detail {
 class FormatterTag {};
-};
+} // namespace detail
 
 /**
  * Formatter class.
  *
- * Note that this class is tricky, as it keeps *references* to its arguments
- * (and doesn't copy the passed-in format string).  Thankfully, you can't use
- * this directly, you have to use format(...) below.
+ * Note that this class is tricky, as it keeps *references* to its lvalue
+ * arguments (while it takes ownership of the temporaries), and it doesn't
+ * copy the passed-in format string. Thankfully, you can't use this
+ * directly, you have to use format(...) below.
  */
 
-/* BaseFormatter class. Currently, the only behavior that can be
- * overridden is the actual formatting of positional parameters in
+/* BaseFormatter class.
+ * Overridable behaviours:
+ * You may override the actual formatting of positional parameters in
  * `doFormatArg`. The Formatter class provides the default implementation.
+ *
+ * You may also override `doFormat` and `getSizeArg`. These override points were
+ * added to permit static analysis of format strings, when it is inconvenient
+ * or impossible to instantiate a BaseFormatter with the correct storage
  */
 template <class Derived, bool containerMode, class... Args>
 class BaseFormatter {
@@ -71,9 +81,9 @@ class BaseFormatter {
    * Append to a string.
    */
   template <class Str>
-  typename std::enable_if<IsSomeString<Str>::value>::type
-  appendTo(Str& str) const {
-    auto appender = [&str] (StringPiece s) { str.append(s.data(), s.size()); };
+  typename std::enable_if<IsSomeString<Str>::value>::type appendTo(
+      Str& str) const {
+    auto appender = [&str](StringPiece s) { str.append(s.data(), s.size()); };
     (*this)(appender);
   }
 
@@ -96,16 +106,19 @@ class BaseFormatter {
   }
 
   /**
-   * metadata to identify generated children of BaseFormatter
+   * Metadata to identify generated children of BaseFormatter
    */
   typedef detail::FormatterTag IsFormatter;
   typedef BaseFormatter BaseType;
 
  private:
-  typedef std::tuple<FormatValue<
-      typename std::decay<Args>::type>...> ValueTuple;
+  typedef std::tuple<Args...> ValueTuple;
   static constexpr size_t valueCount = std::tuple_size<ValueTuple>::value;
 
+  Derived const& asDerived() const {
+    return *static_cast<const Derived*>(this);
+  }
+
   template <size_t K, class Callback>
   typename std::enable_if<K == valueCount>::type
   doFormatFrom(size_t i, FormatArg& arg, Callback& /*cb*/) const {
@@ -116,9 +129,9 @@ class BaseFormatter {
   typename std::enable_if<(K < valueCount)>::type
   doFormatFrom(size_t i, FormatArg& arg, Callback& cb) const {
     if (i == K) {
-      static_cast<const Derived*>(this)->template doFormatArg<K>(arg, cb);
+      asDerived().template doFormatArg<K>(arg, cb);
     } else {
-      doFormatFrom<K+1>(i, arg, cb);
+      doFormatFrom<K + 1>(i, arg, cb);
     }
   }
 
@@ -128,32 +141,36 @@ class BaseFormatter {
   }
 
   template <size_t K>
-  typename std::enable_if<K == valueCount, int>::type
-  getSizeArgFrom(size_t i, const FormatArg& arg) const {
+  typename std::enable_if<K == valueCount, int>::type getSizeArgFrom(
+      size_t i,
+      const FormatArg& arg) const {
     arg.error("argument index out of range, max=", i);
   }
 
   template <class T>
-  typename std::enable_if<std::is_integral<T>::value &&
-                          !std::is_same<T, bool>::value, int>::type
+  typename std::enable_if<
+      std::is_integral<T>::value && !std::is_same<T, bool>::value,
+      int>::type
   getValue(const FormatValue<T>& format, const FormatArg&) const {
     return static_cast<int>(format.getValue());
   }
 
   template <class T>
-  typename std::enable_if<!std::is_integral<T>::value ||
-                          std::is_same<T, bool>::value, int>::type
+  typename std::enable_if<
+      !std::is_integral<T>::value || std::is_same<T, bool>::value,
+      int>::type
   getValue(const FormatValue<T>&, const FormatArg& arg) const {
     arg.error("dynamic field width argument must be integral");
   }
 
   template <size_t K>
-  typename std::enable_if<K < valueCount, int>::type
-  getSizeArgFrom(size_t i, const FormatArg& arg) const {
+      typename std::enable_if <
+      K<valueCount, int>::type getSizeArgFrom(size_t i, const FormatArg& arg)
+          const {
     if (i == K) {
-      return getValue(std::get<K>(values_), arg);
+      return getValue(getFormatValue<K>(), arg);
     }
-    return getSizeArgFrom<K+1>(i, arg);
+    return getSizeArgFrom<K + 1>(i, arg);
   }
 
   int getSizeArg(size_t i, const FormatArg& arg) const {
@@ -173,31 +190,47 @@ class BaseFormatter {
   // for the exclusive use of format() (below).  This way, you can't create
   // a Formatter object, but can handle references to it (for streaming,
   // conversion to string, etc) -- which is good, as Formatter objects are
-  // dangerous (they hold references, possibly to temporaries)
+  // dangerous (they may hold references).
   BaseFormatter(BaseFormatter&&) = default;
   BaseFormatter& operator=(BaseFormatter&&) = default;
 
+  template <size_t K>
+  using ArgType = typename std::tuple_element<K, ValueTuple>::type;
+
+  template <size_t K>
+  FormatValue<typename std::decay<ArgType<K>>::type> getFormatValue() const {
+    return FormatValue<typename std::decay<ArgType<K>>::type>(
+        std::get<K>(values_));
+  }
+
   ValueTuple values_;
 };
 
 template <bool containerMode, class... Args>
-class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
-                                       containerMode,
-                                       Args...> {
+class Formatter : public BaseFormatter<
+                      Formatter<containerMode, Args...>,
+                      containerMode,
+                      Args...> {
  private:
   explicit Formatter(StringPiece& str, Args&&... args)
-      : BaseFormatter<Formatter<containerMode, Args...>,
-                      containerMode,
-                      Args...>(str, std::forward<Args>(args)...) {}
+      : BaseFormatter<
+            Formatter<containerMode, Args...>,
+            containerMode,
+            Args...>(str, std::forward<Args>(args)...) {
+    static_assert(
+        !containerMode || sizeof...(Args) == 1,
+        "Exactly one argument required in container mode");
+  }
 
   template <size_t K, class Callback>
   void doFormatArg(FormatArg& arg, Callback& cb) const {
-    std::get<K>(this->values_).format(arg, cb);
+    this->template getFormatValue<K>().format(arg, cb);
   }
 
-  friend class BaseFormatter<Formatter<containerMode, Args...>,
-                             containerMode,
-                             Args...>;
+  friend class BaseFormatter<
+      Formatter<containerMode, Args...>,
+      containerMode,
+      Args...>;
 
   template <class... A>
   friend Formatter<false, A...> format(StringPiece fmt, A&&... arg);
@@ -208,10 +241,13 @@ class Formatter : public BaseFormatter<Formatter<containerMode, Args...>,
 /**
  * Formatter objects can be written to streams.
  */
-template<bool containerMode, class... Args>
-std::ostream& operator<<(std::ostream& out,
-                         const Formatter<containerMode, Args...>& formatter) {
-  auto writer = [&out] (StringPiece sp) { out.write(sp.data(), sp.size()); };
+template <bool containerMode, class... Args>
+std::ostream& operator<<(
+    std::ostream& out,
+    const Formatter<containerMode, Args...>& formatter) {
+  auto writer = [&out](StringPiece sp) {
+    out.write(sp.data(), std::streamsize(sp.size()));
+  };
   formatter(writer);
   return out;
 }
@@ -220,8 +256,9 @@ std::ostream& operator<<(std::ostream& out,
  * Formatter objects can be written to stdio FILEs.
  */
 template <class Derived, bool containerMode, class... Args>
-void writeTo(FILE* fp,
-             const BaseFormatter<Derived, containerMode, Args...>& formatter);
+void writeTo(
+    FILE* fp,
+    const BaseFormatter<Derived, containerMode, Args...>& formatter);
 
 /**
  * Create a formatter object.
@@ -232,8 +269,7 @@ void writeTo(FILE* fp,
  */
 template <class... Args>
 Formatter<false, Args...> format(StringPiece fmt, Args&&... args) {
-  return Formatter<false, Args...>(
-      fmt, std::forward<Args>(args)...);
+  return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
 }
 
 /**
@@ -260,8 +296,7 @@ inline std::string sformat(StringPiece fmt, Args&&... args) {
  */
 template <class Container>
 Formatter<true, Container> vformat(StringPiece fmt, Container&& container) {
-  return Formatter<true, Container>(
-      fmt, std::forward<Container>(container));
+  return Formatter<true, Container>(fmt, std::forward<Container>(container));
 }
 
 /**
@@ -273,6 +308,33 @@ inline std::string svformat(StringPiece fmt, Container&& container) {
   return vformat(fmt, std::forward<Container>(container)).str();
 }
 
+/**
+ * Exception class thrown when a format key is not found in the given
+ * associative container keyed by strings. We inherit std::out_of_range for
+ * compatibility with callers that expect exception to be thrown directly
+ * by std::map or std::unordered_map.
+ *
+ * Having the key be at the end of the message string, we can access it by
+ * simply adding its offset to what(). Not storing separate std::string key
+ * makes the exception type small and noexcept-copyable like std::out_of_range,
+ * and therefore able to fit in-situ in exception_wrapper.
+ */
+class FOLLY_EXPORT FormatKeyNotFoundException : public std::out_of_range {
+ public:
+  explicit FormatKeyNotFoundException(StringPiece key);
+
+  char const* key() const noexcept {
+    return what() + kMessagePrefix.size();
+  }
+
+ private:
+  static constexpr StringPiece const kMessagePrefix = "format key not found: ";
+};
+
+namespace detail {
+[[noreturn]] void throwFormatKeyNotFoundException(StringPiece key);
+} // namespace detail
+
 /**
  * Wrap a sequence or associative container so that out-of-range lookups
  * return a default value rather than throwing an exception.
@@ -281,20 +343,20 @@ inline std::string svformat(StringPiece fmt, Container&& container) {
  * format("[no_such_key"], defaulted(map, 42))  -> 42
  */
 namespace detail {
-template <class Container, class Value> struct DefaultValueWrapper {
+template <class Container, class Value>
+struct DefaultValueWrapper {
   DefaultValueWrapper(const Container& container, const Value& defaultValue)
-    : container(container),
-      defaultValue(defaultValue) {
-  }
+      : container(container), defaultValue(defaultValue) {}
 
   const Container& container;
   const Value& defaultValue;
 };
-}  // namespace
+} // namespace detail
 
 template <class Container, class Value>
-detail::DefaultValueWrapper<Container, Value>
-defaulted(const Container& c, const Value& v) {
+detail::DefaultValueWrapper<Container, Value> defaulted(
+    const Container& c,
+    const Value& v) {
   return detail::DefaultValueWrapper<Container, Value>(c, v);
 }
 
@@ -343,25 +405,28 @@ void formatString(StringPiece val, FormatArg& arg, FormatCallback& cb);
  * field width")
  */
 template <class FormatCallback>
-void formatNumber(StringPiece val, int prefixLen, FormatArg& arg,
-                  FormatCallback& cb);
-
+void formatNumber(
+    StringPiece val,
+    int prefixLen,
+    FormatArg& arg,
+    FormatCallback& cb);
 
 /**
  * Format a Formatter object recursively.  Behaves just like
  * formatString(fmt.str(), arg, cb); but avoids creating a temporary
  * string if possible.
  */
-template <class FormatCallback,
-          class Derived,
-          bool containerMode,
-          class... Args>
+template <
+    class FormatCallback,
+    class Derived,
+    bool containerMode,
+    class... Args>
 void formatFormatter(
     const BaseFormatter<Derived, containerMode, Args...>& formatter,
     FormatArg& arg,
     FormatCallback& cb);
 
-}  // namespace format_value
+} // namespace format_value
 
 /*
  * Specialize folly::FormatValue for your type.
@@ -396,7 +461,7 @@ struct IsFormatter<
     typename std::enable_if<
         std::is_same<typename T::IsFormatter, detail::FormatterTag>::value>::
         type> : public std::true_type {};
-} // folly::detail
+} // namespace detail
 
 // Deprecated API. formatChecked() et. al. now behave identically to their
 // non-Checked counterparts.
@@ -409,8 +474,9 @@ inline std::string sformatChecked(StringPiece fmt, Args&&... args) {
   return formatChecked(fmt, std::forward<Args>(args)...).str();
 }
 template <class Container>
-Formatter<true, Container> vformatChecked(StringPiece fmt,
-                                          Container&& container) {
+Formatter<true, Container> vformatChecked(
+    StringPiece fmt,
+    Container&& container) {
   return vformat(fmt, std::forward<Container>(container));
 }
 template <class Container>
@@ -428,10 +494,8 @@ vformatChecked(Str* out, StringPiece fmt, Container&& container) {
   vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
 }
 
-}  // namespace folly
+} // namespace folly
 
 #include <folly/Format-inl.h>
 
-#pragma GCC diagnostic pop
-
-#endif /* FOLLY_FORMAT_H_ */
+FOLLY_POP_WARNING