|
|
|||
File indexing completed on 2026-05-10 08:44:30
0001 //===- FormatVariadic.h - Efficient type-safe string formatting --*- C++-*-===// 0002 // 0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 0004 // See https://llvm.org/LICENSE.txt for license information. 0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 0006 // 0007 //===----------------------------------------------------------------------===// 0008 // 0009 // This file implements the formatv() function which can be used with other LLVM 0010 // subsystems to provide printf-like formatting, but with improved safety and 0011 // flexibility. The result of `formatv` is an object which can be streamed to 0012 // a raw_ostream or converted to a std::string or llvm::SmallString. 0013 // 0014 // // Convert to std::string. 0015 // std::string S = formatv("{0} {1}", 1234.412, "test").str(); 0016 // 0017 // // Convert to llvm::SmallString 0018 // SmallString<8> S = formatv("{0} {1}", 1234.412, "test").sstr<8>(); 0019 // 0020 // // Stream to an existing raw_ostream. 0021 // OS << formatv("{0} {1}", 1234.412, "test"); 0022 // 0023 //===----------------------------------------------------------------------===// 0024 0025 #ifndef LLVM_SUPPORT_FORMATVARIADIC_H 0026 #define LLVM_SUPPORT_FORMATVARIADIC_H 0027 0028 #include "llvm/ADT/ArrayRef.h" 0029 #include "llvm/ADT/STLExtras.h" 0030 #include "llvm/ADT/SmallString.h" 0031 #include "llvm/ADT/SmallVector.h" 0032 #include "llvm/ADT/StringRef.h" 0033 #include "llvm/Support/FormatCommon.h" 0034 #include "llvm/Support/FormatProviders.h" 0035 #include "llvm/Support/FormatVariadicDetails.h" 0036 #include "llvm/Support/raw_ostream.h" 0037 #include <array> 0038 #include <cstddef> 0039 #include <optional> 0040 #include <string> 0041 #include <tuple> 0042 #include <utility> 0043 0044 namespace llvm { 0045 0046 enum class ReplacementType { Format, Literal }; 0047 0048 struct ReplacementItem { 0049 explicit ReplacementItem(StringRef Literal) 0050 : Type(ReplacementType::Literal), Spec(Literal) {} 0051 ReplacementItem(StringRef Spec, unsigned Index, unsigned Width, 0052 AlignStyle Where, char Pad, StringRef Options) 0053 : Type(ReplacementType::Format), Spec(Spec), Index(Index), Width(Width), 0054 Where(Where), Pad(Pad), Options(Options) {} 0055 0056 ReplacementType Type; 0057 StringRef Spec; 0058 unsigned Index = 0; 0059 unsigned Width = 0; 0060 AlignStyle Where = AlignStyle::Right; 0061 char Pad = 0; 0062 StringRef Options; 0063 }; 0064 0065 class formatv_object_base { 0066 protected: 0067 StringRef Fmt; 0068 ArrayRef<support::detail::format_adapter *> Adapters; 0069 bool Validate; 0070 0071 formatv_object_base(StringRef Fmt, 0072 ArrayRef<support::detail::format_adapter *> Adapters, 0073 bool Validate) 0074 : Fmt(Fmt), Adapters(Adapters), Validate(Validate) {} 0075 0076 formatv_object_base(formatv_object_base const &rhs) = delete; 0077 formatv_object_base(formatv_object_base &&rhs) = default; 0078 0079 public: 0080 void format(raw_ostream &S) const { 0081 const auto Replacements = parseFormatString(Fmt, Adapters.size(), Validate); 0082 for (const auto &R : Replacements) { 0083 if (R.Type == ReplacementType::Literal) { 0084 S << R.Spec; 0085 continue; 0086 } 0087 if (R.Index >= Adapters.size()) { 0088 S << R.Spec; 0089 continue; 0090 } 0091 0092 auto *W = Adapters[R.Index]; 0093 0094 FmtAlign Align(*W, R.Where, R.Width, R.Pad); 0095 Align.format(S, R.Options); 0096 } 0097 } 0098 0099 // Parse and optionally validate format string (in debug builds). 0100 static SmallVector<ReplacementItem, 2> 0101 parseFormatString(StringRef Fmt, size_t NumArgs, bool Validate); 0102 0103 std::string str() const { 0104 std::string Result; 0105 raw_string_ostream Stream(Result); 0106 Stream << *this; 0107 Stream.flush(); 0108 return Result; 0109 } 0110 0111 template <unsigned N> SmallString<N> sstr() const { 0112 SmallString<N> Result; 0113 raw_svector_ostream Stream(Result); 0114 Stream << *this; 0115 return Result; 0116 } 0117 0118 template <unsigned N> operator SmallString<N>() const { return sstr<N>(); } 0119 0120 operator std::string() const { return str(); } 0121 }; 0122 0123 template <typename Tuple> class formatv_object : public formatv_object_base { 0124 // Storage for the parameter adapters. Since the base class erases the type 0125 // of the parameters, we have to own the storage for the parameters here, and 0126 // have the base class store type-erased pointers into this tuple. 0127 Tuple Parameters; 0128 std::array<support::detail::format_adapter *, std::tuple_size<Tuple>::value> 0129 ParameterPointers; 0130 0131 // The parameters are stored in a std::tuple, which does not provide runtime 0132 // indexing capabilities. In order to enable runtime indexing, we use this 0133 // structure to put the parameters into a std::array. Since the parameters 0134 // are not all the same type, we use some type-erasure by wrapping the 0135 // parameters in a template class that derives from a non-template superclass. 0136 // Essentially, we are converting a std::tuple<Derived<Ts...>> to a 0137 // std::array<Base*>. 0138 struct create_adapters { 0139 template <typename... Ts> 0140 std::array<support::detail::format_adapter *, std::tuple_size<Tuple>::value> 0141 operator()(Ts &...Items) { 0142 return {{&Items...}}; 0143 } 0144 }; 0145 0146 public: 0147 formatv_object(StringRef Fmt, Tuple &&Params, bool Validate) 0148 : formatv_object_base(Fmt, ParameterPointers, Validate), 0149 Parameters(std::move(Params)) { 0150 ParameterPointers = std::apply(create_adapters(), Parameters); 0151 } 0152 0153 formatv_object(formatv_object const &rhs) = delete; 0154 0155 formatv_object(formatv_object &&rhs) 0156 : formatv_object_base(std::move(rhs)), 0157 Parameters(std::move(rhs.Parameters)) { 0158 ParameterPointers = std::apply(create_adapters(), Parameters); 0159 Adapters = ParameterPointers; 0160 } 0161 }; 0162 0163 // Format text given a format string and replacement parameters. 0164 // 0165 // ===General Description=== 0166 // 0167 // Formats textual output. `Fmt` is a string consisting of one or more 0168 // replacement sequences with the following grammar: 0169 // 0170 // rep_field ::= "{" [index] ["," layout] [":" format] "}" 0171 // index ::= <non-negative integer> 0172 // layout ::= [[[char]loc]width] 0173 // format ::= <any string not containing "{" or "}"> 0174 // char ::= <any character except "{" or "}"> 0175 // loc ::= "-" | "=" | "+" 0176 // width ::= <positive integer> 0177 // 0178 // index - An optional non-negative integer specifying the index of the item 0179 // in the parameter pack to print. Any other value is invalid. If its 0180 // not specified, it will be automatically assigned a value based on 0181 // the order of rep_field seen in the format string. Note that mixing 0182 // automatic and explicit index in the same call is an error and will 0183 // fail validation in assert-enabled builds. 0184 // layout - A string controlling how the field is laid out within the available 0185 // space. 0186 // format - A type-dependent string used to provide additional options to 0187 // the formatting operation. Refer to the documentation of the 0188 // various individual format providers for per-type options. 0189 // char - The padding character. Defaults to ' ' (space). Only valid if 0190 // `loc` is also specified. 0191 // loc - Where to print the formatted text within the field. Only valid if 0192 // `width` is also specified. 0193 // '-' : The field is left aligned within the available space. 0194 // '=' : The field is centered within the available space. 0195 // '+' : The field is right aligned within the available space (this 0196 // is the default). 0197 // width - The width of the field within which to print the formatted text. 0198 // If this is less than the required length then the `char` and `loc` 0199 // fields are ignored, and the field is printed with no leading or 0200 // trailing padding. If this is greater than the required length, 0201 // then the text is output according to the value of `loc`, and padded 0202 // as appropriate on the left and/or right by `char`. 0203 // 0204 // ===Special Characters=== 0205 // 0206 // The characters '{' and '}' are reserved and cannot appear anywhere within a 0207 // replacement sequence. Outside of a replacement sequence, in order to print 0208 // a literal '{' it must be doubled as "{{". 0209 // 0210 // ===Parameter Indexing=== 0211 // 0212 // `index` specifies the index of the parameter in the parameter pack to format 0213 // into the output. Note that it is possible to refer to the same parameter 0214 // index multiple times in a given format string. This makes it possible to 0215 // output the same value multiple times without passing it multiple times to the 0216 // function. For example: 0217 // 0218 // formatv("{0} {1} {0}", "a", "bb") 0219 // 0220 // would yield the string "abba". This can be convenient when it is expensive 0221 // to compute the value of the parameter, and you would otherwise have had to 0222 // save it to a temporary. 0223 // 0224 // ===Formatter Search=== 0225 // 0226 // For a given parameter of type T, the following steps are executed in order 0227 // until a match is found: 0228 // 0229 // 1. If the parameter is of class type, and inherits from format_adapter, 0230 // Then format() is invoked on it to produce the formatted output. The 0231 // implementation should write the formatted text into `Stream`. 0232 // 2. If there is a suitable template specialization of format_provider<> 0233 // for type T containing a method whose signature is: 0234 // void format(const T &Obj, raw_ostream &Stream, StringRef Options) 0235 // Then this method is invoked as described in Step 1. 0236 // 3. If an appropriate operator<< for raw_ostream exists, it will be used. 0237 // For this to work, (raw_ostream& << const T&) must return raw_ostream&. 0238 // 0239 // If a match cannot be found through either of the above methods, a compiler 0240 // error is generated. 0241 // 0242 // ===Invalid Format String Handling=== 0243 // 0244 // In the case of a format string which does not match the grammar described 0245 // above, the output is undefined. With asserts enabled, LLVM will trigger an 0246 // assertion. Otherwise, it will try to do something reasonable, but in general 0247 // the details of what that is are undefined. 0248 // 0249 0250 // formatv() with validation enable/disable controlled by the first argument. 0251 template <typename... Ts> 0252 inline auto formatv(bool Validate, const char *Fmt, Ts &&...Vals) { 0253 auto Params = std::make_tuple( 0254 support::detail::build_format_adapter(std::forward<Ts>(Vals))...); 0255 return formatv_object<decltype(Params)>(Fmt, std::move(Params), Validate); 0256 } 0257 0258 // formatv() with validation enabled. 0259 template <typename... Ts> inline auto formatv(const char *Fmt, Ts &&...Vals) { 0260 return formatv<Ts...>(true, Fmt, std::forward<Ts>(Vals)...); 0261 } 0262 0263 } // end namespace llvm 0264 0265 #endif // LLVM_SUPPORT_FORMATVARIADIC_H
| [ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
|
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |
|