LLVM 22.0.0git
Format.h
Go to the documentation of this file.
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"
30#include <cassert>
31#include <cstdio>
32#include <optional>
33#include <tuple>
34#include <utility>
35
36namespace 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.
41protected:
42 const char *Fmt;
43 ~format_object_base() = default; // Disallow polymorphic deletion.
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
50public:
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.
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
81namespace detail {
82template <typename T> struct decay_if_c_char_array {
83 using type = T;
84};
85template <std::size_t N> struct decay_if_c_char_array<char[N]> {
86 using type = const char *;
87};
88template <typename T>
90} // namespace detail
91
92template <typename... Ts>
93class format_object final : public format_object_base {
94 std::tuple<detail::decay_if_c_char_array_t<Ts>...> Vals;
95
96 template <std::size_t... Is>
97 int snprint_tuple(char *Buffer, unsigned BufferSize,
98 std::index_sequence<Is...>) const {
99#ifdef _MSC_VER
100 return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
101#else
102 return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
103#endif
104 }
105
106public:
107 format_object(const char *fmt, const Ts &... vals)
108 : format_object_base(fmt), Vals(vals...) {
109 static_assert(
110 (std::is_scalar_v<detail::decay_if_c_char_array_t<Ts>> && ...),
111 "format can't be used with non fundamental / non pointer type");
112 }
113
114 int snprint(char *Buffer, unsigned BufferSize) const override {
115 return snprint_tuple(Buffer, BufferSize, std::index_sequence_for<Ts...>());
116 }
117};
118
119/// These are helper functions used to produce formatted output. They use
120/// template type deduction to construct the appropriate instance of the
121/// format_object class to simplify their construction.
122///
123/// This is typically used like:
124/// \code
125/// OS << format("%0.4f", myfloat) << '\n';
126/// \endcode
127
128template <typename... Ts>
129inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
130 return format_object<Ts...>(Fmt, Vals...);
131}
132
133/// This is a helper class for left_justify, right_justify, and center_justify.
135public:
138 : Str(S), Width(W), Justify(J) {}
139
140private:
141 StringRef Str;
142 unsigned Width;
143 Justification Justify;
144 friend class raw_ostream;
145};
146
147/// left_justify - append spaces after string so total output is
148/// \p Width characters. If \p Str is larger that \p Width, full string
149/// is written with no padding.
150inline FormattedString left_justify(StringRef Str, unsigned Width) {
152}
153
154/// right_justify - add spaces before string so total output is
155/// \p Width characters. If \p Str is larger that \p Width, full string
156/// is written with no padding.
157inline FormattedString right_justify(StringRef Str, unsigned Width) {
159}
160
161/// center_justify - add spaces before and after string so total output is
162/// \p Width characters. If \p Str is larger that \p Width, full string
163/// is written with no padding.
164inline FormattedString center_justify(StringRef Str, unsigned Width) {
166}
167
168/// This is a helper class used for format_hex() and format_decimal().
170 uint64_t HexValue;
171 int64_t DecValue;
172 unsigned Width;
173 bool Hex;
174 bool Upper;
175 bool HexPrefix;
176 friend class raw_ostream;
177
178public:
179 FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
180 bool Prefix)
181 : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
182 HexPrefix(Prefix) {}
183};
184
185/// format_hex - Output \p N as a fixed width hexadecimal. If number will not
186/// fit in width, full number is still printed. Examples:
187/// OS << format_hex(255, 4) => 0xff
188/// OS << format_hex(255, 4, true) => 0xFF
189/// OS << format_hex(255, 6) => 0x00ff
190/// OS << format_hex(255, 2) => 0xff
191inline FormattedNumber format_hex(uint64_t N, unsigned Width,
192 bool Upper = false) {
193 assert(Width <= 18 && "hex width must be <= 18");
194 return FormattedNumber(N, 0, Width, true, Upper, true);
195}
196
197/// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
198/// prepend '0x' to the outputted string. If number will not fit in width,
199/// full number is still printed. Examples:
200/// OS << format_hex_no_prefix(255, 2) => ff
201/// OS << format_hex_no_prefix(255, 2, true) => FF
202/// OS << format_hex_no_prefix(255, 4) => 00ff
203/// OS << format_hex_no_prefix(255, 1) => ff
205 bool Upper = false) {
206 assert(Width <= 16 && "hex width must be <= 16");
207 return FormattedNumber(N, 0, Width, true, Upper, false);
208}
209
210/// format_decimal - Output \p N as a right justified, fixed-width decimal. If
211/// number will not fit in width, full number is still printed. Examples:
212/// OS << format_decimal(0, 5) => " 0"
213/// OS << format_decimal(255, 5) => " 255"
214/// OS << format_decimal(-1, 3) => " -1"
215/// OS << format_decimal(12345, 3) => "12345"
216inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
217 return FormattedNumber(0, N, Width, false, false, false);
218}
219
221 ArrayRef<uint8_t> Bytes;
222
223 // If not std::nullopt, display offsets for each line relative to starting
224 // value.
225 std::optional<uint64_t> FirstByteOffset;
226 uint32_t IndentLevel; // Number of characters to indent each line.
227 uint32_t NumPerLine; // Number of bytes to show per line.
228 uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
229 bool Upper; // Show offset and hex bytes as upper case.
230 bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
231 friend class raw_ostream;
232
233public:
234 FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, std::optional<uint64_t> O,
235 uint32_t NPL, uint8_t BGS, bool U, bool A)
236 : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
237 ByteGroupSize(BGS), Upper(U), ASCII(A) {
238
239 if (ByteGroupSize > NumPerLine)
240 ByteGroupSize = NumPerLine;
241 }
242};
243
244inline FormattedBytes
246 std::optional<uint64_t> FirstByteOffset = std::nullopt,
247 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
248 uint32_t IndentLevel = 0, bool Upper = false) {
249 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
250 ByteGroupSize, Upper, false);
251}
252
253inline FormattedBytes
255 std::optional<uint64_t> FirstByteOffset = std::nullopt,
256 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
257 uint32_t IndentLevel = 0, bool Upper = false) {
258 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
259 ByteGroupSize, Upper, true);
260}
261
262} // end namespace llvm
263
264#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define H(x, y, z)
Definition MD5.cpp:57
#define T
This file contains some templates that are useful if you are working with the STL at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
friend class raw_ostream
Definition Format.h:231
FormattedBytes(ArrayRef< uint8_t > B, uint32_t IL, std::optional< uint64_t > O, uint32_t NPL, uint8_t BGS, bool U, bool A)
Definition Format.h:234
This is a helper class used for format_hex() and format_decimal().
Definition Format.h:169
friend class raw_ostream
Definition Format.h:176
FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, bool Prefix)
Definition Format.h:179
This is a helper class for left_justify, right_justify, and center_justify.
Definition Format.h:134
FormattedString(StringRef S, unsigned W, Justification J)
Definition Format.h:137
friend class raw_ostream
Definition Format.h:144
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
format_object_base(const char *fmt)
Definition Format.h:51
unsigned print(char *Buffer, unsigned BufferSize) const
Format the object into the specified buffer.
Definition Format.h:56
const char * Fmt
Definition Format.h:42
virtual int snprint(char *Buffer, unsigned BufferSize) const =0
Call snprintf() for this object, on the given buffer and size.
format_object_base(const format_object_base &)=default
format_object(const char *fmt, const Ts &... vals)
Definition Format.h:107
int snprint(char *Buffer, unsigned BufferSize) const override
Call snprintf() for this object, on the given buffer and size.
Definition Format.h:114
typename decay_if_c_char_array< T >::type decay_if_c_char_array_t
Definition Format.h:89
This is an optimization pass for GlobalISel generic memory operations.
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition Format.h:216
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition Format.h:157
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition Format.h:164
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition Format.h:191
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition Format.h:204
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
FormattedBytes format_bytes_with_ascii(ArrayRef< uint8_t > Bytes, std::optional< uint64_t > FirstByteOffset=std::nullopt, uint32_t NumPerLine=16, uint8_t ByteGroupSize=4, uint32_t IndentLevel=0, bool Upper=false)
Definition Format.h:254
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition Format.h:150
FormattedBytes format_bytes(ArrayRef< uint8_t > Bytes, std::optional< uint64_t > FirstByteOffset=std::nullopt, uint32_t NumPerLine=16, uint8_t ByteGroupSize=4, uint32_t IndentLevel=0, bool Upper=false)
Definition Format.h:245
#define N