LLVM 24.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"
31#include <cassert>
32#include <cstdio>
33#include <optional>
34#include <tuple>
35#include <utility>
36
37namespace llvm {
38
39/// These are templated helper classes used by the format function that
40/// capture the object to be formatted and the format string. When actually
41/// printed, this synthesizes the string into a temporary buffer provided and
42/// returns whether or not it is big enough.
43
44namespace detail {
45template <typename T> struct decay_if_c_char_array {
46 using type = T;
47};
48template <std::size_t N> struct decay_if_c_char_array<char[N]> {
49 using type = const char *;
50};
51template <typename T>
53} // namespace detail
54
55template <typename... Ts> class format_object {
56 const char *Fmt;
57 std::tuple<detail::decay_if_c_char_array_t<Ts>...> Vals;
58
59 template <std::size_t... Is>
60 int snprint_tuple(char *Buffer, unsigned BufferSize,
61 std::index_sequence<Is...>) const {
62 return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
63 }
64
65public:
66 format_object(const char *fmt, const Ts &...vals) : Fmt(fmt), Vals(vals...) {
67 static_assert(
68 (std::is_scalar_v<detail::decay_if_c_char_array_t<Ts>> && ...),
69 "format can't be used with non fundamental / non pointer type");
70 }
71
72 int snprint(char *Buffer, unsigned BufferSize) const {
73 return snprint_tuple(Buffer, BufferSize, std::index_sequence_for<Ts...>());
74 }
75};
76
77template <typename... Ts>
79 // Stream through an explicitly-typed function_ref. Passing the lambda
80 // directly is ambiguous when block pointer conversions are enabled due to a
81 // competing raw_ostream::operator<<(const void *) candidate. This ambiguity
82 // affects the Swift compiler because it contains Swift code that
83 // interoperates with C++ code that instantiates this template, and Swift's
84 // C++ interoperability enables block pointer conversions.
85 auto Print = [&Fmt](char *Buf, size_t Size) -> int {
86 return Fmt.snprint(Buf, Size);
87 };
88 OS << function_ref<int(char *, size_t)>(Print);
89 return OS;
90}
91
92/// These are helper functions used to produce formatted output. They use
93/// template type deduction to construct the appropriate instance of the
94/// format_object class to simplify their construction.
95///
96/// This is typically used like:
97/// \code
98/// OS << format("%0.4f", myfloat) << '\n';
99/// \endcode
100
101template <typename... Ts>
102inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
103 return format_object<Ts...>(Fmt, Vals...);
104}
105
106/// This is a helper class for left_justify, right_justify, and center_justify.
108public:
111 : Str(S), Width(W), Justify(J) {}
112
113private:
114 StringRef Str;
115 unsigned Width;
116 Justification Justify;
117 friend class raw_ostream;
118};
119
120/// left_justify - append spaces after string so total output is
121/// \p Width characters. If \p Str is larger that \p Width, full string
122/// is written with no padding.
123inline FormattedString left_justify(StringRef Str, unsigned Width) {
125}
126
127/// right_justify - add spaces before string so total output is
128/// \p Width characters. If \p Str is larger that \p Width, full string
129/// is written with no padding.
130inline FormattedString right_justify(StringRef Str, unsigned Width) {
132}
133
134/// center_justify - add spaces before and after string so total output is
135/// \p Width characters. If \p Str is larger that \p Width, full string
136/// is written with no padding.
137inline FormattedString center_justify(StringRef Str, unsigned Width) {
139}
140
141/// This is a helper class used for format_hex() and format_decimal().
143 uint64_t HexValue;
144 int64_t DecValue;
145 unsigned Width;
146 bool Hex;
147 bool Upper;
148 bool HexPrefix;
149 friend class raw_ostream;
150
151public:
152 FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
153 bool Prefix)
154 : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
155 HexPrefix(Prefix) {}
156};
157
158/// format_hex - Output \p N as a fixed width hexadecimal. If number will not
159/// fit in width, full number is still printed. Examples:
160/// OS << format_hex(255, 4) => 0xff
161/// OS << format_hex(255, 4, true) => 0xFF
162/// OS << format_hex(255, 6) => 0x00ff
163/// OS << format_hex(255, 2) => 0xff
164inline FormattedNumber format_hex(uint64_t N, unsigned Width,
165 bool Upper = false) {
166 assert(Width <= 18 && "hex width must be <= 18");
167 return FormattedNumber(N, 0, Width, true, Upper, true);
168}
169
170/// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
171/// prepend '0x' to the outputted string. If number will not fit in width,
172/// full number is still printed. Examples:
173/// OS << format_hex_no_prefix(255, 2) => ff
174/// OS << format_hex_no_prefix(255, 2, true) => FF
175/// OS << format_hex_no_prefix(255, 4) => 00ff
176/// OS << format_hex_no_prefix(255, 1) => ff
178 bool Upper = false) {
179 assert(Width <= 16 && "hex width must be <= 16");
180 return FormattedNumber(N, 0, Width, true, Upper, false);
181}
182
183/// format_decimal - Output \p N as a right justified, fixed-width decimal. If
184/// number will not fit in width, full number is still printed. Examples:
185/// OS << format_decimal(0, 5) => " 0"
186/// OS << format_decimal(255, 5) => " 255"
187/// OS << format_decimal(-1, 3) => " -1"
188/// OS << format_decimal(12345, 3) => "12345"
189inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
190 return FormattedNumber(0, N, Width, false, false, false);
191}
192
194 ArrayRef<uint8_t> Bytes;
195
196 // If not std::nullopt, display offsets for each line relative to starting
197 // value.
198 std::optional<uint64_t> FirstByteOffset;
199 uint32_t IndentLevel; // Number of characters to indent each line.
200 uint32_t NumPerLine; // Number of bytes to show per line.
201 uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
202 bool Upper; // Show offset and hex bytes as upper case.
203 bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
204 friend class raw_ostream;
205
206public:
207 FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, std::optional<uint64_t> O,
208 uint32_t NPL, uint8_t BGS, bool U, bool A)
209 : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
210 ByteGroupSize(BGS), Upper(U), ASCII(A) {
211
212 if (ByteGroupSize > NumPerLine)
213 ByteGroupSize = NumPerLine;
214 }
215};
216
217inline FormattedBytes
219 std::optional<uint64_t> FirstByteOffset = std::nullopt,
220 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
221 uint32_t IndentLevel = 0, bool Upper = false) {
222 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
223 ByteGroupSize, Upper, false);
224}
225
226inline FormattedBytes
228 std::optional<uint64_t> FirstByteOffset = std::nullopt,
229 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
230 uint32_t IndentLevel = 0, bool Upper = false) {
231 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
232 ByteGroupSize, Upper, true);
233}
234
235} // end namespace llvm
236
237#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 H(x, y, z)
Definition MD5.cpp:56
#define T
This file contains some templates that are useful if you are working with the STL at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
friend class raw_ostream
Definition Format.h:204
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:207
This is a helper class used for format_hex() and format_decimal().
Definition Format.h:142
friend class raw_ostream
Definition Format.h:149
FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, bool Prefix)
Definition Format.h:152
This is a helper class for left_justify, right_justify, and center_justify.
Definition Format.h:107
FormattedString(StringRef S, unsigned W, Justification J)
Definition Format.h:110
friend class raw_ostream
Definition Format.h:117
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
format_object(const char *fmt, const Ts &...vals)
Definition Format.h:66
int snprint(char *Buffer, unsigned BufferSize) const
Definition Format.h:72
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
Definition ADL.h:123
typename decay_if_c_char_array< T >::type decay_if_c_char_array_t
Definition Format.h:52
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:189
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition Format.h:130
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition Format.h:137
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition Format.h:164
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:177
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
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:227
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition Format.h:123
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
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:218
#define N