FormatVariadic.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //===- FormatVariadic.h - Efficient type-safe string formatting --*- C++-*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the formatv() function which can be used with other LLVM
  10. // subsystems to provide printf-like formatting, but with improved safety and
  11. // flexibility. The result of `formatv` is an object which can be streamed to
  12. // a raw_ostream or converted to a std::string or llvm::SmallString.
  13. //
  14. // // Convert to std::string.
  15. // std::string S = formatv("{0} {1}", 1234.412, "test").str();
  16. //
  17. // // Convert to llvm::SmallString
  18. // SmallString<8> S = formatv("{0} {1}", 1234.412, "test").sstr<8>();
  19. //
  20. // // Stream to an existing raw_ostream.
  21. // OS << formatv("{0} {1}", 1234.412, "test");
  22. //
  23. //===----------------------------------------------------------------------===//
  24. #ifndef LLVM_SUPPORT_FORMATVARIADIC_H
  25. #define LLVM_SUPPORT_FORMATVARIADIC_H
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/Optional.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/ADT/SmallString.h"
  30. #include "llvm/ADT/StringRef.h"
  31. #include "llvm/Support/FormatCommon.h"
  32. #include "llvm/Support/FormatProviders.h"
  33. #include "llvm/Support/FormatVariadicDetails.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <cstddef>
  36. #include <string>
  37. #include <tuple>
  38. #include <utility>
  39. #include <vector>
  40. namespace llvm {
  41. enum class ReplacementType { Empty, Format, Literal };
  42. struct ReplacementItem {
  43. ReplacementItem() = default;
  44. explicit ReplacementItem(StringRef Literal)
  45. : Type(ReplacementType::Literal), Spec(Literal) {}
  46. ReplacementItem(StringRef Spec, size_t Index, size_t Align, AlignStyle Where,
  47. char Pad, StringRef Options)
  48. : Type(ReplacementType::Format), Spec(Spec), Index(Index), Align(Align),
  49. Where(Where), Pad(Pad), Options(Options) {}
  50. ReplacementType Type = ReplacementType::Empty;
  51. StringRef Spec;
  52. size_t Index = 0;
  53. size_t Align = 0;
  54. AlignStyle Where = AlignStyle::Right;
  55. char Pad = 0;
  56. StringRef Options;
  57. };
  58. class formatv_object_base {
  59. protected:
  60. StringRef Fmt;
  61. ArrayRef<detail::format_adapter *> Adapters;
  62. static bool consumeFieldLayout(StringRef &Spec, AlignStyle &Where,
  63. size_t &Align, char &Pad);
  64. static std::pair<ReplacementItem, StringRef>
  65. splitLiteralAndReplacement(StringRef Fmt);
  66. formatv_object_base(StringRef Fmt,
  67. ArrayRef<detail::format_adapter *> Adapters)
  68. : Fmt(Fmt), Adapters(Adapters) {}
  69. formatv_object_base(formatv_object_base const &rhs) = delete;
  70. formatv_object_base(formatv_object_base &&rhs) = default;
  71. public:
  72. void format(raw_ostream &S) const {
  73. for (auto &R : parseFormatString(Fmt)) {
  74. if (R.Type == ReplacementType::Empty)
  75. continue;
  76. if (R.Type == ReplacementType::Literal) {
  77. S << R.Spec;
  78. continue;
  79. }
  80. if (R.Index >= Adapters.size()) {
  81. S << R.Spec;
  82. continue;
  83. }
  84. auto W = Adapters[R.Index];
  85. FmtAlign Align(*W, R.Where, R.Align, R.Pad);
  86. Align.format(S, R.Options);
  87. }
  88. }
  89. static SmallVector<ReplacementItem, 2> parseFormatString(StringRef Fmt);
  90. static Optional<ReplacementItem> parseReplacementItem(StringRef Spec);
  91. std::string str() const {
  92. std::string Result;
  93. raw_string_ostream Stream(Result);
  94. Stream << *this;
  95. Stream.flush();
  96. return Result;
  97. }
  98. template <unsigned N> SmallString<N> sstr() const {
  99. SmallString<N> Result;
  100. raw_svector_ostream Stream(Result);
  101. Stream << *this;
  102. return Result;
  103. }
  104. template <unsigned N> operator SmallString<N>() const { return sstr<N>(); }
  105. operator std::string() const { return str(); }
  106. };
  107. template <typename Tuple> class formatv_object : public formatv_object_base {
  108. // Storage for the parameter adapters. Since the base class erases the type
  109. // of the parameters, we have to own the storage for the parameters here, and
  110. // have the base class store type-erased pointers into this tuple.
  111. Tuple Parameters;
  112. std::array<detail::format_adapter *, std::tuple_size<Tuple>::value>
  113. ParameterPointers;
  114. // The parameters are stored in a std::tuple, which does not provide runtime
  115. // indexing capabilities. In order to enable runtime indexing, we use this
  116. // structure to put the parameters into a std::array. Since the parameters
  117. // are not all the same type, we use some type-erasure by wrapping the
  118. // parameters in a template class that derives from a non-template superclass.
  119. // Essentially, we are converting a std::tuple<Derived<Ts...>> to a
  120. // std::array<Base*>.
  121. struct create_adapters {
  122. template <typename... Ts>
  123. std::array<detail::format_adapter *, std::tuple_size<Tuple>::value>
  124. operator()(Ts &... Items) {
  125. return {{&Items...}};
  126. }
  127. };
  128. public:
  129. formatv_object(StringRef Fmt, Tuple &&Params)
  130. : formatv_object_base(Fmt, ParameterPointers),
  131. Parameters(std::move(Params)) {
  132. ParameterPointers = apply_tuple(create_adapters(), Parameters);
  133. }
  134. formatv_object(formatv_object const &rhs) = delete;
  135. formatv_object(formatv_object &&rhs)
  136. : formatv_object_base(std::move(rhs)),
  137. Parameters(std::move(rhs.Parameters)) {
  138. ParameterPointers = apply_tuple(create_adapters(), Parameters);
  139. Adapters = ParameterPointers;
  140. }
  141. };
  142. // Format text given a format string and replacement parameters.
  143. //
  144. // ===General Description===
  145. //
  146. // Formats textual output. `Fmt` is a string consisting of one or more
  147. // replacement sequences with the following grammar:
  148. //
  149. // rep_field ::= "{" [index] ["," layout] [":" format] "}"
  150. // index ::= <non-negative integer>
  151. // layout ::= [[[char]loc]width]
  152. // format ::= <any string not containing "{" or "}">
  153. // char ::= <any character except "{" or "}">
  154. // loc ::= "-" | "=" | "+"
  155. // width ::= <positive integer>
  156. //
  157. // index - A non-negative integer specifying the index of the item in the
  158. // parameter pack to print. Any other value is invalid.
  159. // layout - A string controlling how the field is laid out within the available
  160. // space.
  161. // format - A type-dependent string used to provide additional options to
  162. // the formatting operation. Refer to the documentation of the
  163. // various individual format providers for per-type options.
  164. // char - The padding character. Defaults to ' ' (space). Only valid if
  165. // `loc` is also specified.
  166. // loc - Where to print the formatted text within the field. Only valid if
  167. // `width` is also specified.
  168. // '-' : The field is left aligned within the available space.
  169. // '=' : The field is centered within the available space.
  170. // '+' : The field is right aligned within the available space (this
  171. // is the default).
  172. // width - The width of the field within which to print the formatted text.
  173. // If this is less than the required length then the `char` and `loc`
  174. // fields are ignored, and the field is printed with no leading or
  175. // trailing padding. If this is greater than the required length,
  176. // then the text is output according to the value of `loc`, and padded
  177. // as appropriate on the left and/or right by `char`.
  178. //
  179. // ===Special Characters===
  180. //
  181. // The characters '{' and '}' are reserved and cannot appear anywhere within a
  182. // replacement sequence. Outside of a replacement sequence, in order to print
  183. // a literal '{' it must be doubled as "{{".
  184. //
  185. // ===Parameter Indexing===
  186. //
  187. // `index` specifies the index of the parameter in the parameter pack to format
  188. // into the output. Note that it is possible to refer to the same parameter
  189. // index multiple times in a given format string. This makes it possible to
  190. // output the same value multiple times without passing it multiple times to the
  191. // function. For example:
  192. //
  193. // formatv("{0} {1} {0}", "a", "bb")
  194. //
  195. // would yield the string "abba". This can be convenient when it is expensive
  196. // to compute the value of the parameter, and you would otherwise have had to
  197. // save it to a temporary.
  198. //
  199. // ===Formatter Search===
  200. //
  201. // For a given parameter of type T, the following steps are executed in order
  202. // until a match is found:
  203. //
  204. // 1. If the parameter is of class type, and inherits from format_adapter,
  205. // Then format() is invoked on it to produce the formatted output. The
  206. // implementation should write the formatted text into `Stream`.
  207. // 2. If there is a suitable template specialization of format_provider<>
  208. // for type T containing a method whose signature is:
  209. // void format(const T &Obj, raw_ostream &Stream, StringRef Options)
  210. // Then this method is invoked as described in Step 1.
  211. // 3. If an appropriate operator<< for raw_ostream exists, it will be used.
  212. // For this to work, (raw_ostream& << const T&) must return raw_ostream&.
  213. //
  214. // If a match cannot be found through either of the above methods, a compiler
  215. // error is generated.
  216. //
  217. // ===Invalid Format String Handling===
  218. //
  219. // In the case of a format string which does not match the grammar described
  220. // above, the output is undefined. With asserts enabled, LLVM will trigger an
  221. // assertion. Otherwise, it will try to do something reasonable, but in general
  222. // the details of what that is are undefined.
  223. //
  224. template <typename... Ts>
  225. inline auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object<decltype(
  226. std::make_tuple(detail::build_format_adapter(std::forward<Ts>(Vals))...))> {
  227. using ParamTuple = decltype(
  228. std::make_tuple(detail::build_format_adapter(std::forward<Ts>(Vals))...));
  229. return formatv_object<ParamTuple>(
  230. Fmt,
  231. std::make_tuple(detail::build_format_adapter(std::forward<Ts>(Vals))...));
  232. }
  233. } // end namespace llvm
  234. #endif // LLVM_SUPPORT_FORMATVARIADIC_H