FormatVariadic.h 10 KB

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