LLVM 23.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 OS <<
80 [&Fmt](char *Buf, size_t Size) -> int { return Fmt.snprint(Buf, Size); };
81 return OS;
82}
83
84/// These are helper functions used to produce formatted output. They use
85/// template type deduction to construct the appropriate instance of the
86/// format_object class to simplify their construction.
87///
88/// This is typically used like:
89/// \code
90/// OS << format("%0.4f", myfloat) << '\n';
91/// \endcode
92
93template <typename... Ts>
94inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
95 return format_object<Ts...>(Fmt, Vals...);
96}
97
98/// This is a helper class for left_justify, right_justify, and center_justify.
100public:
103 : Str(S), Width(W), Justify(J) {}
104
105private:
106 StringRef Str;
107 unsigned Width;
108 Justification Justify;
109 friend class raw_ostream;
110};
111
112/// left_justify - append spaces after string so total output is
113/// \p Width characters. If \p Str is larger that \p Width, full string
114/// is written with no padding.
115inline FormattedString left_justify(StringRef Str, unsigned Width) {
117}
118
119/// right_justify - add spaces before string so total output is
120/// \p Width characters. If \p Str is larger that \p Width, full string
121/// is written with no padding.
122inline FormattedString right_justify(StringRef Str, unsigned Width) {
124}
125
126/// center_justify - add spaces before and after string so total output is
127/// \p Width characters. If \p Str is larger that \p Width, full string
128/// is written with no padding.
129inline FormattedString center_justify(StringRef Str, unsigned Width) {
131}
132
133/// This is a helper class used for format_hex() and format_decimal().
135 uint64_t HexValue;
136 int64_t DecValue;
137 unsigned Width;
138 bool Hex;
139 bool Upper;
140 bool HexPrefix;
141 friend class raw_ostream;
142
143public:
144 FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
145 bool Prefix)
146 : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
147 HexPrefix(Prefix) {}
148};
149
150/// format_hex - Output \p N as a fixed width hexadecimal. If number will not
151/// fit in width, full number is still printed. Examples:
152/// OS << format_hex(255, 4) => 0xff
153/// OS << format_hex(255, 4, true) => 0xFF
154/// OS << format_hex(255, 6) => 0x00ff
155/// OS << format_hex(255, 2) => 0xff
156inline FormattedNumber format_hex(uint64_t N, unsigned Width,
157 bool Upper = false) {
158 assert(Width <= 18 && "hex width must be <= 18");
159 return FormattedNumber(N, 0, Width, true, Upper, true);
160}
161
162/// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
163/// prepend '0x' to the outputted string. If number will not fit in width,
164/// full number is still printed. Examples:
165/// OS << format_hex_no_prefix(255, 2) => ff
166/// OS << format_hex_no_prefix(255, 2, true) => FF
167/// OS << format_hex_no_prefix(255, 4) => 00ff
168/// OS << format_hex_no_prefix(255, 1) => ff
170 bool Upper = false) {
171 assert(Width <= 16 && "hex width must be <= 16");
172 return FormattedNumber(N, 0, Width, true, Upper, false);
173}
174
175/// format_decimal - Output \p N as a right justified, fixed-width decimal. If
176/// number will not fit in width, full number is still printed. Examples:
177/// OS << format_decimal(0, 5) => " 0"
178/// OS << format_decimal(255, 5) => " 255"
179/// OS << format_decimal(-1, 3) => " -1"
180/// OS << format_decimal(12345, 3) => "12345"
181inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
182 return FormattedNumber(0, N, Width, false, false, false);
183}
184
186 ArrayRef<uint8_t> Bytes;
187
188 // If not std::nullopt, display offsets for each line relative to starting
189 // value.
190 std::optional<uint64_t> FirstByteOffset;
191 uint32_t IndentLevel; // Number of characters to indent each line.
192 uint32_t NumPerLine; // Number of bytes to show per line.
193 uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces
194 bool Upper; // Show offset and hex bytes as upper case.
195 bool ASCII; // Show the ASCII bytes for the hex bytes to the right.
196 friend class raw_ostream;
197
198public:
199 FormattedBytes(ArrayRef<uint8_t> B, uint32_t IL, std::optional<uint64_t> O,
200 uint32_t NPL, uint8_t BGS, bool U, bool A)
201 : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL),
202 ByteGroupSize(BGS), Upper(U), ASCII(A) {
203
204 if (ByteGroupSize > NumPerLine)
205 ByteGroupSize = NumPerLine;
206 }
207};
208
209inline FormattedBytes
211 std::optional<uint64_t> FirstByteOffset = std::nullopt,
212 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
213 uint32_t IndentLevel = 0, bool Upper = false) {
214 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
215 ByteGroupSize, Upper, false);
216}
217
218inline FormattedBytes
220 std::optional<uint64_t> FirstByteOffset = std::nullopt,
221 uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4,
222 uint32_t IndentLevel = 0, bool Upper = false) {
223 return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine,
224 ByteGroupSize, Upper, true);
225}
226
227} // end namespace llvm
228
229#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:196
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:199
This is a helper class used for format_hex() and format_decimal().
Definition Format.h:134
friend class raw_ostream
Definition Format.h:141
FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, bool Prefix)
Definition Format.h:144
This is a helper class for left_justify, right_justify, and center_justify.
Definition Format.h:99
FormattedString(StringRef S, unsigned W, Justification J)
Definition Format.h:102
friend class raw_ostream
Definition Format.h:109
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:181
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition Format.h:122
FormattedString center_justify(StringRef Str, unsigned Width)
center_justify - add spaces before and after string so total output is Width characters.
Definition Format.h:129
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition Format.h:156
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:169
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
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:219
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition Format.h:115
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:210
#define N