1//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the raw_ostream class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_RAW_OSTREAM_H
15#define LLVM_SUPPORT_RAW_OSTREAM_H
16
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/StringRef.h"
19#include <cassert>
20#include <cstddef>
21#include <cstdint>
22#include <cstring>
23#include <string>
24#include <system_error>
25
26namespace llvm {
27
28class formatv_object_base;
29class format_object_base;
30class FormattedString;
31class FormattedNumber;
32class FormattedBytes;
33
34namespace sys {
35namespace fs {
36enum FileAccess : unsigned;
37enum OpenFlags : unsigned;
38enum CreationDisposition : unsigned;
39} // end namespace fs
40} // end namespace sys
41
42/// This class implements an extremely fast bulk output stream that can *only*
43/// output to a stream. It does not support seeking, reopening, rewinding, line
44/// buffered disciplines etc. It is a simple buffer that outputs
45/// a chunk at a time.
46class raw_ostream {
47private:
48 /// The buffer is handled in such a way that the buffer is
49 /// uninitialized, unbuffered, or out of space when OutBufCur >=
50 /// OutBufEnd. Thus a single comparison suffices to determine if we
51 /// need to take the slow path to write a single character.
52 ///
53 /// The buffer is in one of three states:
54 /// 1. Unbuffered (BufferMode == Unbuffered)
55 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
56 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
57 /// OutBufEnd - OutBufStart >= 1).
58 ///
59 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
60 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
61 /// managed by the subclass.
62 ///
63 /// If a subclass installs an external buffer using SetBuffer then it can wait
64 /// for a \see write_impl() call to handle the data which has been put into
65 /// this buffer.
66 char *OutBufStart, *OutBufEnd, *OutBufCur;
67
68 enum BufferKind {
69 Unbuffered = 0,
70 InternalBuffer,
71 ExternalBuffer
72 } BufferMode;
73
74public:
75 // color order matches ANSI escape sequence, don't change
76 enum Colors {
77 BLACK = 0,
78 RED,
79 GREEN,
80 YELLOW,
81 BLUE,
82 MAGENTA,
83 CYAN,
84 WHITE,
85 SAVEDCOLOR
86 };
87
88 explicit raw_ostream(bool unbuffered = false)
89 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
90 // Start out ready to flush.
91 OutBufStart = OutBufEnd = OutBufCur = nullptr;
92 }
93
94 raw_ostream(const raw_ostream &) = delete;
95 void operator=(const raw_ostream &) = delete;
96
97 virtual ~raw_ostream();
98
99 /// tell - Return the current offset with the file.
100 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
101
102 //===--------------------------------------------------------------------===//
103 // Configuration Interface
104 //===--------------------------------------------------------------------===//
105
106 /// Set the stream to be buffered, with an automatically determined buffer
107 /// size.
108 void SetBuffered();
109
110 /// Set the stream to be buffered, using the specified buffer size.
111 void SetBufferSize(size_t Size) {
112 flush();
113 SetBufferAndMode(new char[Size], Size, InternalBuffer);
114 }
115
116 size_t GetBufferSize() const {
117 // If we're supposed to be buffered but haven't actually gotten around
118 // to allocating the buffer yet, return the value that would be used.
119 if (BufferMode != Unbuffered && OutBufStart == nullptr)
120 return preferred_buffer_size();
121
122 // Otherwise just return the size of the allocated buffer.
123 return OutBufEnd - OutBufStart;
124 }
125
126 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
127 /// after every write. This routine will also flush the buffer immediately
128 /// when the stream is being set to unbuffered.
129 void SetUnbuffered() {
130 flush();
131 SetBufferAndMode(nullptr, 0, Unbuffered);
132 }
133
134 size_t GetNumBytesInBuffer() const {
135 return OutBufCur - OutBufStart;
136 }
137
138 //===--------------------------------------------------------------------===//
139 // Data Output Interface
140 //===--------------------------------------------------------------------===//
141
142 void flush() {
143 if (OutBufCur != OutBufStart)
144 flush_nonempty();
145 }
146
147 raw_ostream &operator<<(char C) {
148 if (OutBufCur >= OutBufEnd)
149 return write(C);
150 *OutBufCur++ = C;
151 return *this;
152 }
153
154 raw_ostream &operator<<(unsigned char C) {
155 if (OutBufCur >= OutBufEnd)
156 return write(C);
157 *OutBufCur++ = C;
158 return *this;
159 }
160
161 raw_ostream &operator<<(signed char C) {
162 if (OutBufCur >= OutBufEnd)
163 return write(C);
164 *OutBufCur++ = C;
165 return *this;
166 }
167
168 raw_ostream &operator<<(StringRef Str) {
169 // Inline fast path, particularly for strings with a known length.
170 size_t Size = Str.size();
171
172 // Make sure we can use the fast path.
173 if (Size > (size_t)(OutBufEnd - OutBufCur))
174 return write(Str.data(), Size);
175
176 if (Size) {
177 memcpy(OutBufCur, Str.data(), Size);
178 OutBufCur += Size;
179 }
180 return *this;
181 }
182
183 raw_ostream &operator<<(const char *Str) {
184 // Inline fast path, particularly for constant strings where a sufficiently
185 // smart compiler will simplify strlen.
186
187 return this->operator<<(StringRef(Str));
188 }
189
190 raw_ostream &operator<<(const std::string &Str) {
191 // Avoid the fast path, it would only increase code size for a marginal win.
192 return write(Str.data(), Str.length());
193 }
194
195 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
196 return write(Str.data(), Str.size());
197 }
198
199 raw_ostream &operator<<(unsigned long N);
200 raw_ostream &operator<<(long N);
201 raw_ostream &operator<<(unsigned long long N);
202 raw_ostream &operator<<(long long N);
203 raw_ostream &operator<<(const void *P);
204
205 raw_ostream &operator<<(unsigned int N) {
206 return this->operator<<(static_cast<unsigned long>(N));
207 }
208
209 raw_ostream &operator<<(int N) {
210 return this->operator<<(static_cast<long>(N));
211 }
212
213 raw_ostream &operator<<(double N);
214
215 /// Output \p N in hexadecimal, without any prefix or padding.
216 raw_ostream &write_hex(unsigned long long N);
217
218 /// Output a formatted UUID with dash separators.
219 using uuid_t = uint8_t[16];
220 raw_ostream &write_uuid(const uuid_t UUID);
221
222 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
223 /// satisfy llvm::isPrint into an escape sequence.
224 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
225
226 raw_ostream &write(unsigned char C);
227 raw_ostream &write(const char *Ptr, size_t Size);
228
229 // Formatted output, see the format() function in Support/Format.h.
230 raw_ostream &operator<<(const format_object_base &Fmt);
231
232 // Formatted output, see the leftJustify() function in Support/Format.h.
233 raw_ostream &operator<<(const FormattedString &);
234
235 // Formatted output, see the formatHex() function in Support/Format.h.
236 raw_ostream &operator<<(const FormattedNumber &);
237
238 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
239 raw_ostream &operator<<(const formatv_object_base &);
240
241 // Formatted output, see the format_bytes() function in Support/Format.h.
242 raw_ostream &operator<<(const FormattedBytes &);
243
244 /// indent - Insert 'NumSpaces' spaces.
245 raw_ostream &indent(unsigned NumSpaces);
246
247 /// write_zeros - Insert 'NumZeros' nulls.
248 raw_ostream &write_zeros(unsigned NumZeros);
249
250 /// Changes the foreground color of text that will be output from this point
251 /// forward.
252 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
253 /// change only the bold attribute, and keep colors untouched
254 /// @param Bold bold/brighter text, default false
255 /// @param BG if true change the background, default: change foreground
256 /// @returns itself so it can be used within << invocations
257 virtual raw_ostream &changeColor(enum Colors Color,
258 bool Bold = false,
259 bool BG = false) {
260 (void)Color;
261 (void)Bold;
262 (void)BG;
263 return *this;
264 }
265
266 /// Resets the colors to terminal defaults. Call this when you are done
267 /// outputting colored text, or before program exit.
268 virtual raw_ostream &resetColor() { return *this; }
269
270 /// Reverses the foreground and background colors.
271 virtual raw_ostream &reverseColor() { return *this; }
272
273 /// This function determines if this stream is connected to a "tty" or
274 /// "console" window. That is, the output would be displayed to the user
275 /// rather than being put on a pipe or stored in a file.
276 virtual bool is_displayed() const { return false; }
277
278 /// This function determines if this stream is displayed and supports colors.
279 virtual bool has_colors() const { return is_displayed(); }
280
281 //===--------------------------------------------------------------------===//
282 // Subclass Interface
283 //===--------------------------------------------------------------------===//
284
285private:
286 /// The is the piece of the class that is implemented by subclasses. This
287 /// writes the \p Size bytes starting at
288 /// \p Ptr to the underlying stream.
289 ///
290 /// This function is guaranteed to only be called at a point at which it is
291 /// safe for the subclass to install a new buffer via SetBuffer.
292 ///
293 /// \param Ptr The start of the data to be written. For buffered streams this
294 /// is guaranteed to be the start of the buffer.
295 ///
296 /// \param Size The number of bytes to be written.
297 ///
298 /// \invariant { Size > 0 }
299 virtual void write_impl(const char *Ptr, size_t Size) = 0;
300
301 /// Return the current position within the stream, not counting the bytes
302 /// currently in the buffer.
303 virtual uint64_t current_pos() const = 0;
304
305protected:
306 /// Use the provided buffer as the raw_ostream buffer. This is intended for
307 /// use only by subclasses which can arrange for the output to go directly
308 /// into the desired output buffer, instead of being copied on each flush.
309 void SetBuffer(char *BufferStart, size_t Size) {
310 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
311 }
312
313 /// Return an efficient buffer size for the underlying output mechanism.
314 virtual size_t preferred_buffer_size() const;
315
316 /// Return the beginning of the current stream buffer, or 0 if the stream is
317 /// unbuffered.
318 const char *getBufferStart() const { return OutBufStart; }
319
320 //===--------------------------------------------------------------------===//
321 // Private Interface
322 //===--------------------------------------------------------------------===//
323private:
324 /// Install the given buffer and mode.
325 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
326
327 /// Flush the current buffer, which is known to be non-empty. This outputs the
328 /// currently buffered data and resets the buffer to empty.
329 void flush_nonempty();
330
331 /// Copy data into the buffer. Size must not be greater than the number of
332 /// unused bytes in the buffer.
333 void copy_to_buffer(const char *Ptr, size_t Size);
334
335 virtual void anchor();
336};
337
338/// An abstract base class for streams implementations that also support a
339/// pwrite operation. This is useful for code that can mostly stream out data,
340/// but needs to patch in a header that needs to know the output size.
341class raw_pwrite_stream : public raw_ostream {
342 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
343 void anchor() override;
344
345public:
346 explicit raw_pwrite_stream(bool Unbuffered = false)
347 : raw_ostream(Unbuffered) {}
348 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
349#ifndef NDBEBUG
350 uint64_t Pos = tell();
351 // /dev/null always reports a pos of 0, so we cannot perform this check
352 // in that case.
353 if (Pos)
354 assert(Size + Offset <= Pos && "We don't support extending the stream");
355#endif
356 pwrite_impl(Ptr, Size, Offset);
357 }
358};
359
360//===----------------------------------------------------------------------===//
361// File Output Streams
362//===----------------------------------------------------------------------===//
363
364/// A raw_ostream that writes to a file descriptor.
365///
366class raw_fd_ostream : public raw_pwrite_stream {
367 int FD;
368 bool ShouldClose;
369
370 bool SupportsSeeking;
371
372#ifdef _WIN32
373 /// True if this fd refers to a Windows console device. Mintty and other
374 /// terminal emulators are TTYs, but they are not consoles.
375 bool IsWindowsConsole = false;
376#endif
377
378 std::error_code EC;
379
380 uint64_t pos;
381
382 /// See raw_ostream::write_impl.
383 void write_impl(const char *Ptr, size_t Size) override;
384
385 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
386
387 /// Return the current position within the stream, not counting the bytes
388 /// currently in the buffer.
389 uint64_t current_pos() const override { return pos; }
390
391 /// Determine an efficient buffer size.
392 size_t preferred_buffer_size() const override;
393
394 /// Set the flag indicating that an output error has been encountered.
395 void error_detected(std::error_code EC) { this->EC = EC; }
396
397 void anchor() override;
398
399public:
400 /// Open the specified file for writing. If an error occurs, information
401 /// about the error is put into EC, and the stream should be immediately
402 /// destroyed;
403 /// \p Flags allows optional flags to control how the file will be opened.
404 ///
405 /// As a special case, if Filename is "-", then the stream will use
406 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
407 /// descriptor.
408 raw_fd_ostream(StringRef Filename, std::error_code &EC);
409 raw_fd_ostream(StringRef Filename, std::error_code &EC,
410 sys::fs::CreationDisposition Disp);
411 raw_fd_ostream(StringRef Filename, std::error_code &EC,
412 sys::fs::FileAccess Access);
413 raw_fd_ostream(StringRef Filename, std::error_code &EC,
414 sys::fs::OpenFlags Flags);
415 raw_fd_ostream(StringRef Filename, std::error_code &EC,
416 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
417 sys::fs::OpenFlags Flags);
418
419 /// FD is the file descriptor that this writes to. If ShouldClose is true,
420 /// this closes the file when the stream is destroyed. If FD is for stdout or
421 /// stderr, it will not be closed.
422 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
423
424 ~raw_fd_ostream() override;
425
426 /// Manually flush the stream and close the file. Note that this does not call
427 /// fsync.
428 void close();
429
430 bool supportsSeeking() { return SupportsSeeking; }
431
432 /// Flushes the stream and repositions the underlying file descriptor position
433 /// to the offset specified from the beginning of the file.
434 uint64_t seek(uint64_t off);
435
436 raw_ostream &changeColor(enum Colors colors, bool bold=false,
437 bool bg=false) override;
438 raw_ostream &resetColor() override;
439
440 raw_ostream &reverseColor() override;
441
442 bool is_displayed() const override;
443
444 bool has_colors() const override;
445
446 std::error_code error() const { return EC; }
447
448 /// Return the value of the flag in this raw_fd_ostream indicating whether an
449 /// output error has been encountered.
450 /// This doesn't implicitly flush any pending output. Also, it doesn't
451 /// guarantee to detect all errors unless the stream has been closed.
452 bool has_error() const { return bool(EC); }
453
454 /// Set the flag read by has_error() to false. If the error flag is set at the
455 /// time when this raw_ostream's destructor is called, report_fatal_error is
456 /// called to report the error. Use clear_error() after handling the error to
457 /// avoid this behavior.
458 ///
459 /// "Errors should never pass silently.
460 /// Unless explicitly silenced."
461 /// - from The Zen of Python, by Tim Peters
462 ///
463 void clear_error() { EC = std::error_code(); }
464};
465
466/// This returns a reference to a raw_ostream for standard output. Use it like:
467/// outs() << "foo" << "bar";
468raw_ostream &outs();
469
470/// This returns a reference to a raw_ostream for standard error. Use it like:
471/// errs() << "foo" << "bar";
472raw_ostream &errs();
473
474/// This returns a reference to a raw_ostream which simply discards output.
475raw_ostream &nulls();
476
477//===----------------------------------------------------------------------===//
478// Output Stream Adaptors
479//===----------------------------------------------------------------------===//
480
481/// A raw_ostream that writes to an std::string. This is a simple adaptor
482/// class. This class does not encounter output errors.
483class raw_string_ostream : public raw_ostream {
484 std::string &OS;
485
486 /// See raw_ostream::write_impl.
487 void write_impl(const char *Ptr, size_t Size) override;
488
489 /// Return the current position within the stream, not counting the bytes
490 /// currently in the buffer.
491 uint64_t current_pos() const override { return OS.size(); }
492
493public:
494 explicit raw_string_ostream(std::string &O) : OS(O) {}
495 ~raw_string_ostream() override;
496
497 /// Flushes the stream contents to the target string and returns the string's
498 /// reference.
499 std::string& str() {
500 flush();
501 return OS;
502 }
503};
504
505/// A raw_ostream that writes to an SmallVector or SmallString. This is a
506/// simple adaptor class. This class does not encounter output errors.
507/// raw_svector_ostream operates without a buffer, delegating all memory
508/// management to the SmallString. Thus the SmallString is always up-to-date,
509/// may be used directly and there is no need to call flush().
510class raw_svector_ostream : public raw_pwrite_stream {
511 SmallVectorImpl<char> &OS;
512
513 /// See raw_ostream::write_impl.
514 void write_impl(const char *Ptr, size_t Size) override;
515
516 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
517
518 /// Return the current position within the stream.
519 uint64_t current_pos() const override;
520
521public:
522 /// Construct a new raw_svector_ostream.
523 ///
524 /// \param O The vector to write to; this should generally have at least 128
525 /// bytes free to avoid any extraneous memory overhead.
526 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
527 SetUnbuffered();
528 }
529
530 ~raw_svector_ostream() override = default;
531
532 void flush() = delete;
533
534 /// Return a StringRef for the vector contents.
535 StringRef str() { return StringRef(OS.data(), OS.size()); }
536};
537
538/// A raw_ostream that discards all output.
539class raw_null_ostream : public raw_pwrite_stream {
540 /// See raw_ostream::write_impl.
541 void write_impl(const char *Ptr, size_t size) override;
542 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
543
544 /// Return the current position within the stream, not counting the bytes
545 /// currently in the buffer.
546 uint64_t current_pos() const override;
547
548public:
549 explicit raw_null_ostream() = default;
550 ~raw_null_ostream() override;
551};
552
553class buffer_ostream : public raw_svector_ostream {
554 raw_ostream &OS;
555 SmallVector<char, 0> Buffer;
556
557 virtual void anchor() override;
558
559public:
560 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
561 ~buffer_ostream() override { OS << str(); }
562};
563
564} // end namespace llvm
565
566#endif // LLVM_SUPPORT_RAW_OSTREAM_H
567