1 //===- Format.h - Efficient printf-style formatting for streams -*- 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 format() function, which can be used with other 10 // LLVM subsystems to provide printf-style formatting. This gives all the power 11 // and risk of printf. This can be used like this (with raw_ostreams as an 12 // example): 13 // 14 // OS << "mynumber: " << format("%4.5f", 1234.412) << '\n'; 15 // 16 // Or if you prefer: 17 // 18 // OS << format("mynumber: %4.5f\n", 1234.412); 19 // 20 //===----------------------------------------------------------------------===// 21 22 #ifndef LLVM_SUPPORT_FORMAT_H 23 #define LLVM_SUPPORT_FORMAT_H 24 25 #include "llvm/ADT/ArrayRef.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/Support/Compiler.h" 29 #include "llvm/Support/DataTypes.h" 30 #include <cassert> 31 #include <cstdio> 32 #include <optional> 33 #include <tuple> 34 #include <utility> 35 36 namespace llvm { 37 38 /// This is a helper class used for handling formatted output. It is the 39 /// abstract base class of a templated derived class. 40 class LLVM_ABI format_object_base { 41 protected: 42 const char *Fmt; 43 ~format_object_base() = default; // Disallow polymorphic deletion. 44 format_object_base(const format_object_base &) = default; 45 virtual void home(); // Out of line virtual method. 46 47 /// Call snprintf() for this object, on the given buffer and size. 48 virtual int snprint(char *Buffer, unsigned BufferSize) const = 0; 49 50 public: format_object_base(const char * fmt)51 format_object_base(const char *fmt) : Fmt(fmt) {} 52 53 /// Format the object into the specified buffer. On success, this returns 54 /// the length of the formatted string. If the buffer is too small, this 55 /// returns a length to retry with, which will be larger than BufferSize. print(char * Buffer,unsigned BufferSize)56 unsigned print(char *Buffer, unsigned BufferSize) const { 57 assert(BufferSize && "Invalid buffer size!"); 58 59 // Print the string, leaving room for the terminating null. 60 int N = snprint(Buffer, BufferSize); 61 62 // VC++ and old GlibC return negative on overflow, just double the size. 63 if (N < 0) 64 return BufferSize * 2; 65 66 // Other implementations yield number of bytes needed, not including the 67 // final '\0'. 68 if (unsigned(N) >= BufferSize) 69 return N + 1; 70 71 // Otherwise N is the length of output (not including the final '\0'). 72 return N; 73 } 74 }; 75 76 /// These are templated helper classes used by the format function that 77 /// capture the object to be formatted and the format string. When actually 78 /// printed, this synthesizes the string into a temporary buffer provided and 79 /// returns whether or not it is big enough. 80 81 // Helper to validate that format() parameters are scalars or pointers. 82 template <typename... Args> struct validate_format_parameters; 83 template <typename Arg, typename... Args> 84 struct validate_format_parameters<Arg, Args...> { 85 static_assert(std::is_scalar_v<Arg>, 86 "format can't be used with non fundamental / non pointer type"); 87 validate_format_parameters() { validate_format_parameters<Args...>(); } 88 }; 89 template <> struct validate_format_parameters<> {}; 90 91 template <typename... Ts> 92 class format_object final : public format_object_base { 93 std::tuple<Ts...> Vals; 94 95 template <std::size_t... Is> 96 int snprint_tuple(char *Buffer, unsigned BufferSize, 97 std::index_sequence<Is...>) const { 98 #ifdef _MSC_VER 99 return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...); 100 #else 101 return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...); 102 #endif 103 } 104 105 public: 106 format_object(const char *fmt, const Ts &... vals) 107 : format_object_base(fmt), Vals(vals...) { 108 validate_format_parameters<Ts...>(); 109 } 110 111 int snprint(char *Buffer, unsigned BufferSize) const override { 112 return snprint_tuple(Buffer, BufferSize, std::index_sequence_for<Ts...>()); 113 } 114 }; 115 116 /// These are helper functions used to produce formatted output. They use 117 /// template type deduction to construct the appropriate instance of the 118 /// format_object class to simplify their construction. 119 /// 120 /// This is typically used like: 121 /// \code 122 /// OS << format("%0.4f", myfloat) << '\n'; 123 /// \endcode 124 125 template <typename... Ts> 126 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) { 127 return format_object<Ts...>(Fmt, Vals...); 128 } 129 130 /// This is a helper class for left_justify, right_justify, and center_justify. 131 class FormattedString { 132 public: 133 enum Justification { JustifyNone, JustifyLeft, JustifyRight, JustifyCenter }; 134 FormattedString(StringRef S, unsigned W, Justification J) 135 : Str(S), Width(W), Justify(J) {} 136 137 private: 138 StringRef Str; 139 unsigned Width; 140 Justification Justify; 141 friend class raw_ostream; 142 }; 143 144 /// left_justify - append spaces after string so total output is 145 /// \p Width characters. If \p Str is larger that \p Width, full string 146 /// is written with no padding. 147 inline FormattedString left_justify(StringRef Str, unsigned Width) { 148 return FormattedString(Str, Width, FormattedString::JustifyLeft); 149 } 150 151 /// right_justify - add spaces before string so total output is 152 /// \p Width characters. If \p Str is larger that \p Width, full string 153 /// is written with no padding. 154 inline FormattedString right_justify(StringRef Str, unsigned Width) { 155 return FormattedString(Str, Width, FormattedString::JustifyRight); 156 } 157 158 /// center_justify - add spaces before and after string so total output is 159 /// \p Width characters. If \p Str is larger that \p Width, full string 160 /// is written with no padding. 161 inline FormattedString center_justify(StringRef Str, unsigned Width) { 162 return FormattedString(Str, Width, FormattedString::JustifyCenter); 163 } 164 165 /// This is a helper class used for format_hex() and format_decimal(). 166 class FormattedNumber { 167 uint64_t HexValue; 168 int64_t DecValue; 169 unsigned Width; 170 bool Hex; 171 bool Upper; 172 bool HexPrefix; 173 friend class raw_ostream; 174 175 public: 176 FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, 177 bool Prefix) 178 : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U), 179 HexPrefix(Prefix) {} 180 }; 181 182 /// format_hex - Output \p N as a fixed width hexadecimal. If number will not 183 /// fit in width, full number is still printed. Examples: 184 /// OS << format_hex(255, 4) => 0xff 185 /// OS << format_hex(255, 4, true) => 0xFF 186 /// OS << format_hex(255, 6) => 0x00ff 187 /// OS << format_hex(255, 2) => 0xff 188 inline FormattedNumber format_hex(uint64_t N, unsigned Width, 189 bool Upper = false) { 190 assert(Width <= 18 && "hex width must be <= 18"); 191 return FormattedNumber(N, 0, Width, true, Upper, true); 192 } 193 194 /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not 195 /// prepend '0x' to the outputted string. If number will not fit in width, 196 /// full number is still printed. Examples: 197 /// OS << format_hex_no_prefix(255, 2) => ff 198 /// OS << format_hex_no_prefix(255, 2, true) => FF 199 /// OS << format_hex_no_prefix(255, 4) => 00ff 200 /// OS << format_hex_no_prefix(255, 1) => ff 201 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, 202 bool Upper = false) { 203 assert(Width <= 16 && "hex width must be <= 16"); 204 return FormattedNumber(N, 0, Width, true, Upper, false); 205 } 206 207 /// format_decimal - Output \p N as a right justified, fixed-width decimal. If 208 /// number will not fit in width, full number is still printed. Examples: 209 /// OS << format_decimal(0, 5) => " 0" 210 /// OS << format_decimal(255, 5) => " 255" 211 /// OS << format_decimal(-1, 3) => " -1" 212 /// OS << format_decimal(12345, 3) => "12345" 213 inline FormattedNumber format_decimal(int64_t N, unsigned Width) { 214 return FormattedNumber(0, N, Width, false, false, false); 215 } 216 217 class FormattedBytes { 218 ArrayRef<uint8_t> Bytes; 219 220 // If not std::nullopt, display offsets for each line relative to starting 221 // value. 222 std::optional<uint64_t> FirstByteOffset; 223 uint32_t IndentLevel; // Number of characters to indent each line. 224 uint32_t NumPerLine; // Number of bytes to show per line. 225 uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces 226 bool Upper; // Show offset and hex bytes as upper case. 227 bool ASCII; // Show the ASCII bytes for the hex bytes to the right. 228 friend class raw_ostream; 229 230 public: 231 FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, std::optional<uint64_t> O, 232 uint32_t NPL, uint8_t BGS, bool U, bool A) 233 : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL), 234 ByteGroupSize(BGS), Upper(U), ASCII(A) { 235 236 if (ByteGroupSize > NumPerLine) 237 ByteGroupSize = NumPerLine; 238 } 239 }; 240 241 inline FormattedBytes 242 format_bytes(ArrayRef<uint8_t> Bytes, 243 std::optional<uint64_t> FirstByteOffset = std::nullopt, 244 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4, 245 uint32_t IndentLevel = 0, bool Upper = false) { 246 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine, 247 ByteGroupSize, Upper, false); 248 } 249 250 inline FormattedBytes 251 format_bytes_with_ascii(ArrayRef<uint8_t> Bytes, 252 std::optional<uint64_t> FirstByteOffset = std::nullopt, 253 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4, 254 uint32_t IndentLevel = 0, bool Upper = false) { 255 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine, 256 ByteGroupSize, Upper, true); 257 } 258 259 } // end namespace llvm 260 261 #endif 262