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
81// Helper to validate that format() parameters are scalars or pointers.
82template <typename... Args> struct validate_format_parameters;
83template <typename Arg, typename... Args>
84struct 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");
88};
89template <> struct validate_format_parameters<> {};
90
91template <typename... Ts>
92class 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
105public:
106 format_object(const char *fmt, const Ts &... vals)
107 : format_object_base(fmt), Vals(vals...) {
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
125template <typename... Ts>
126inline 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.
132public:
135 : Str(S), Width(W), Justify(J) {}
136
137private:
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.
147inline FormattedString left_justify(StringRef Str, unsigned Width) {
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.
154inline FormattedString right_justify(StringRef Str, unsigned Width) {
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.
161inline FormattedString center_justify(StringRef Str, unsigned Width) {
163}
164
165/// This is a helper class used for format_hex() and format_decimal().
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
175public:
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
188inline 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
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"
213inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
214 return FormattedNumber(0, N, Width, false, false, false);
215}
216
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
230public:
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
241inline FormattedBytes
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
250inline FormattedBytes
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
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_ABI
Definition: Compiler.h:213
#define H(x, y, z)
Definition: MD5.cpp:57
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
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:231
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:166
FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, bool Prefix)
Definition: Format.h:176
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:131
FormattedString(StringRef S, unsigned W, Justification J)
Definition: Format.h:134
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
This is a helper class used for handling formatted output.
Definition: Format.h:40
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:106
int snprint(char *Buffer, unsigned BufferSize) const override
Call snprintf() for this object, on the given buffer and size.
Definition: Format.h:111
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FormattedNumber format_decimal(int64_t N, unsigned Width)
format_decimal - Output N as a right justified, fixed-width decimal.
Definition: Format.h:213
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition: Format.h:154
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition: Format.h:161
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:188
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:201
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:126
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:251
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:147
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:242
#define N
These are templated helper classes used by the format function that capture the object to be formatte...
Definition: Format.h:82