1 //===--- raw_ostream.h - Raw output stream ----------------------*- 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 defines the raw_ostream class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H 14 #define LLVM_SUPPORT_RAW_OSTREAM_H 15 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Support/Compiler.h" 19 #include "llvm/Support/DataTypes.h" 20 #include <cassert> 21 #include <cstddef> 22 #include <cstdint> 23 #include <cstring> 24 #include <optional> 25 #include <string> 26 #include <string_view> 27 #include <system_error> 28 #include <type_traits> 29 30 namespace llvm { 31 32 class Duration; 33 class formatv_object_base; 34 class format_object_base; 35 class FormattedString; 36 class FormattedNumber; 37 class FormattedBytes; 38 template <class T> class [[nodiscard]] Expected; 39 40 namespace sys { 41 namespace fs { 42 enum FileAccess : unsigned; 43 enum OpenFlags : unsigned; 44 enum CreationDisposition : unsigned; 45 class FileLocker; 46 } // end namespace fs 47 } // end namespace sys 48 49 /// This class implements an extremely fast bulk output stream that can *only* 50 /// output to a stream. It does not support seeking, reopening, rewinding, line 51 /// buffered disciplines etc. It is a simple buffer that outputs 52 /// a chunk at a time. 53 class LLVM_ABI raw_ostream { 54 public: 55 // Class kinds to support LLVM-style RTTI. 56 enum class OStreamKind { 57 OK_OStream, 58 OK_FDStream, 59 OK_SVecStream, 60 }; 61 62 private: 63 OStreamKind Kind; 64 65 /// The buffer is handled in such a way that the buffer is 66 /// uninitialized, unbuffered, or out of space when OutBufCur >= 67 /// OutBufEnd. Thus a single comparison suffices to determine if we 68 /// need to take the slow path to write a single character. 69 /// 70 /// The buffer is in one of three states: 71 /// 1. Unbuffered (BufferMode == Unbuffered) 72 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0). 73 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 && 74 /// OutBufEnd - OutBufStart >= 1). 75 /// 76 /// If buffered, then the raw_ostream owns the buffer if (BufferMode == 77 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is 78 /// managed by the subclass. 79 /// 80 /// If a subclass installs an external buffer using SetBuffer then it can wait 81 /// for a \see write_impl() call to handle the data which has been put into 82 /// this buffer. 83 char *OutBufStart, *OutBufEnd, *OutBufCur; 84 bool ColorEnabled = false; 85 86 enum class BufferKind { 87 Unbuffered = 0, 88 InternalBuffer, 89 ExternalBuffer 90 } BufferMode; 91 92 public: 93 // color order matches ANSI escape sequence, don't change 94 enum class Colors { 95 BLACK = 0, 96 RED, 97 GREEN, 98 YELLOW, 99 BLUE, 100 MAGENTA, 101 CYAN, 102 WHITE, 103 BRIGHT_BLACK, 104 BRIGHT_RED, 105 BRIGHT_GREEN, 106 BRIGHT_YELLOW, 107 BRIGHT_BLUE, 108 BRIGHT_MAGENTA, 109 BRIGHT_CYAN, 110 BRIGHT_WHITE, 111 SAVEDCOLOR, 112 RESET, 113 }; 114 115 static constexpr Colors BLACK = Colors::BLACK; 116 static constexpr Colors RED = Colors::RED; 117 static constexpr Colors GREEN = Colors::GREEN; 118 static constexpr Colors YELLOW = Colors::YELLOW; 119 static constexpr Colors BLUE = Colors::BLUE; 120 static constexpr Colors MAGENTA = Colors::MAGENTA; 121 static constexpr Colors CYAN = Colors::CYAN; 122 static constexpr Colors WHITE = Colors::WHITE; 123 static constexpr Colors BRIGHT_BLACK = Colors::BRIGHT_BLACK; 124 static constexpr Colors BRIGHT_RED = Colors::BRIGHT_RED; 125 static constexpr Colors BRIGHT_GREEN = Colors::BRIGHT_GREEN; 126 static constexpr Colors BRIGHT_YELLOW = Colors::BRIGHT_YELLOW; 127 static constexpr Colors BRIGHT_BLUE = Colors::BRIGHT_BLUE; 128 static constexpr Colors BRIGHT_MAGENTA = Colors::BRIGHT_MAGENTA; 129 static constexpr Colors BRIGHT_CYAN = Colors::BRIGHT_CYAN; 130 static constexpr Colors BRIGHT_WHITE = Colors::BRIGHT_WHITE; 131 static constexpr Colors SAVEDCOLOR = Colors::SAVEDCOLOR; 132 static constexpr Colors RESET = Colors::RESET; 133 134 explicit raw_ostream(bool unbuffered = false, 135 OStreamKind K = OStreamKind::OK_OStream) Kind(K)136 : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered 137 : BufferKind::InternalBuffer) { 138 // Start out ready to flush. 139 OutBufStart = OutBufEnd = OutBufCur = nullptr; 140 } 141 142 raw_ostream(const raw_ostream &) = delete; 143 void operator=(const raw_ostream &) = delete; 144 145 virtual ~raw_ostream(); 146 147 /// tell - Return the current offset with the file. tell()148 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); } 149 get_kind()150 OStreamKind get_kind() const { return Kind; } 151 152 //===--------------------------------------------------------------------===// 153 // Configuration Interface 154 //===--------------------------------------------------------------------===// 155 156 /// If possible, pre-allocate \p ExtraSize bytes for stream data. 157 /// i.e. it extends internal buffers to keep additional ExtraSize bytes. 158 /// So that the stream could keep at least tell() + ExtraSize bytes 159 /// without re-allocations. reserveExtraSpace() does not change 160 /// the size/data of the stream. reserveExtraSpace(uint64_t ExtraSize)161 virtual void reserveExtraSpace(uint64_t ExtraSize) { (void)ExtraSize; } 162 163 /// Set the stream to be buffered, with an automatically determined buffer 164 /// size. 165 void SetBuffered(); 166 167 /// Set the stream to be buffered, using the specified buffer size. SetBufferSize(size_t Size)168 void SetBufferSize(size_t Size) { 169 flush(); 170 SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer); 171 } 172 GetBufferSize()173 size_t GetBufferSize() const { 174 // If we're supposed to be buffered but haven't actually gotten around 175 // to allocating the buffer yet, return the value that would be used. 176 if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr) 177 return preferred_buffer_size(); 178 179 // Otherwise just return the size of the allocated buffer. 180 return OutBufEnd - OutBufStart; 181 } 182 183 /// Set the stream to be unbuffered. When unbuffered, the stream will flush 184 /// after every write. This routine will also flush the buffer immediately 185 /// when the stream is being set to unbuffered. SetUnbuffered()186 void SetUnbuffered() { 187 flush(); 188 SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered); 189 } 190 GetNumBytesInBuffer()191 size_t GetNumBytesInBuffer() const { 192 return OutBufCur - OutBufStart; 193 } 194 195 //===--------------------------------------------------------------------===// 196 // Data Output Interface 197 //===--------------------------------------------------------------------===// 198 flush()199 void flush() { 200 if (OutBufCur != OutBufStart) 201 flush_nonempty(); 202 } 203 204 raw_ostream &operator<<(char C) { 205 if (OutBufCur >= OutBufEnd) 206 return write(C); 207 *OutBufCur++ = C; 208 return *this; 209 } 210 211 raw_ostream &operator<<(unsigned char C) { 212 if (OutBufCur >= OutBufEnd) 213 return write(C); 214 *OutBufCur++ = C; 215 return *this; 216 } 217 218 raw_ostream &operator<<(signed char C) { 219 if (OutBufCur >= OutBufEnd) 220 return write(C); 221 *OutBufCur++ = C; 222 return *this; 223 } 224 225 raw_ostream &operator<<(StringRef Str) { 226 // Inline fast path, particularly for strings with a known length. 227 size_t Size = Str.size(); 228 229 // Make sure we can use the fast path. 230 if (Size > (size_t)(OutBufEnd - OutBufCur)) 231 return write(Str.data(), Size); 232 233 if (Size) { 234 memcpy(OutBufCur, Str.data(), Size); 235 OutBufCur += Size; 236 } 237 return *this; 238 } 239 240 #if defined(__cpp_char8_t) 241 // When using `char8_t *` integers or pointers are written to the ostream 242 // instead of UTF-8 code as one might expect. This might lead to unexpected 243 // behavior, especially as `u8""` literals are of type `char8_t*` instead of 244 // type `char_t*` from C++20 onwards. Thus we disallow using them with 245 // raw_ostreams. 246 // If you have u8"" literals to stream, you can rewrite them as ordinary 247 // literals with escape sequences 248 // e.g. replace `u8"\u00a0"` by `"\xc2\xa0"` 249 // or use `reinterpret_cast`: 250 // e.g. replace `u8"\u00a0"` by `reinterpret_cast<const char *>(u8"\u00a0")` 251 raw_ostream &operator<<(const char8_t *Str) = delete; 252 #endif 253 254 raw_ostream &operator<<(const char *Str) { 255 // Inline fast path, particularly for constant strings where a sufficiently 256 // smart compiler will simplify strlen. 257 258 return this->operator<<(StringRef(Str)); 259 } 260 261 raw_ostream &operator<<(const std::string &Str) { 262 // Avoid the fast path, it would only increase code size for a marginal win. 263 return write(Str.data(), Str.length()); 264 } 265 266 raw_ostream &operator<<(const std::string_view &Str) { 267 return write(Str.data(), Str.length()); 268 } 269 270 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) { 271 return write(Str.data(), Str.size()); 272 } 273 274 raw_ostream &operator<<(unsigned long N); 275 raw_ostream &operator<<(long N); 276 raw_ostream &operator<<(unsigned long long N); 277 raw_ostream &operator<<(long long N); 278 raw_ostream &operator<<(const void *P); 279 280 raw_ostream &operator<<(unsigned int N) { 281 return this->operator<<(static_cast<unsigned long>(N)); 282 } 283 284 raw_ostream &operator<<(int N) { 285 return this->operator<<(static_cast<long>(N)); 286 } 287 288 raw_ostream &operator<<(double N); 289 290 /// Output \p N in hexadecimal, without any prefix or padding. 291 raw_ostream &write_hex(unsigned long long N); 292 293 // Change the foreground color of text. 294 raw_ostream &operator<<(Colors C); 295 296 /// Output a formatted UUID with dash separators. 297 using uuid_t = uint8_t[16]; 298 raw_ostream &write_uuid(const uuid_t UUID); 299 300 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't 301 /// satisfy llvm::isPrint into an escape sequence. 302 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false); 303 304 raw_ostream &write(unsigned char C); 305 raw_ostream &write(const char *Ptr, size_t Size); 306 307 // Formatted output, see the format() function in Support/Format.h. 308 raw_ostream &operator<<(const format_object_base &Fmt); 309 310 // Formatted output, see the leftJustify() function in Support/Format.h. 311 raw_ostream &operator<<(const FormattedString &); 312 313 // Formatted output, see the formatHex() function in Support/Format.h. 314 raw_ostream &operator<<(const FormattedNumber &); 315 316 // Formatted output, see the formatv() function in Support/FormatVariadic.h. 317 raw_ostream &operator<<(const formatv_object_base &); 318 319 // Formatted output, see the format_bytes() function in Support/Format.h. 320 raw_ostream &operator<<(const FormattedBytes &); 321 322 /// indent - Insert 'NumSpaces' spaces. 323 raw_ostream &indent(unsigned NumSpaces); 324 325 /// write_zeros - Insert 'NumZeros' nulls. 326 raw_ostream &write_zeros(unsigned NumZeros); 327 328 /// Changes the foreground color of text that will be output from this point 329 /// forward. 330 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to 331 /// change only the bold attribute, and keep colors untouched 332 /// @param Bold bold/brighter text, default false 333 /// @param BG if true change the background, default: change foreground 334 /// @returns itself so it can be used within << invocations 335 virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false, 336 bool BG = false); 337 338 /// Resets the colors to terminal defaults. Call this when you are done 339 /// outputting colored text, or before program exit. 340 virtual raw_ostream &resetColor(); 341 342 /// Reverses the foreground and background colors. 343 virtual raw_ostream &reverseColor(); 344 345 /// This function determines if this stream is connected to a "tty" or 346 /// "console" window. That is, the output would be displayed to the user 347 /// rather than being put on a pipe or stored in a file. is_displayed()348 virtual bool is_displayed() const { return false; } 349 350 /// This function determines if this stream is displayed and supports colors. 351 /// The result is unaffected by calls to enable_color(). has_colors()352 virtual bool has_colors() const { return is_displayed(); } 353 354 // Enable or disable colors. Once enable_colors(false) is called, 355 // changeColor() has no effect until enable_colors(true) is called. enable_colors(bool enable)356 virtual void enable_colors(bool enable) { ColorEnabled = enable; } 357 colors_enabled()358 bool colors_enabled() const { return ColorEnabled; } 359 360 //===--------------------------------------------------------------------===// 361 // Subclass Interface 362 //===--------------------------------------------------------------------===// 363 364 private: 365 /// The is the piece of the class that is implemented by subclasses. This 366 /// writes the \p Size bytes starting at 367 /// \p Ptr to the underlying stream. 368 /// 369 /// This function is guaranteed to only be called at a point at which it is 370 /// safe for the subclass to install a new buffer via SetBuffer. 371 /// 372 /// \param Ptr The start of the data to be written. For buffered streams this 373 /// is guaranteed to be the start of the buffer. 374 /// 375 /// \param Size The number of bytes to be written. 376 /// 377 /// \invariant { Size > 0 } 378 virtual void write_impl(const char *Ptr, size_t Size) = 0; 379 380 /// Return the current position within the stream, not counting the bytes 381 /// currently in the buffer. 382 virtual uint64_t current_pos() const = 0; 383 384 protected: 385 /// Use the provided buffer as the raw_ostream buffer. This is intended for 386 /// use only by subclasses which can arrange for the output to go directly 387 /// into the desired output buffer, instead of being copied on each flush. SetBuffer(char * BufferStart,size_t Size)388 void SetBuffer(char *BufferStart, size_t Size) { 389 SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer); 390 } 391 392 /// Return an efficient buffer size for the underlying output mechanism. 393 virtual size_t preferred_buffer_size() const; 394 395 /// Return the beginning of the current stream buffer, or 0 if the stream is 396 /// unbuffered. getBufferStart()397 const char *getBufferStart() const { return OutBufStart; } 398 399 //===--------------------------------------------------------------------===// 400 // Private Interface 401 //===--------------------------------------------------------------------===// 402 private: 403 /// Install the given buffer and mode. 404 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode); 405 406 /// Flush the current buffer, which is known to be non-empty. This outputs the 407 /// currently buffered data and resets the buffer to empty. 408 void flush_nonempty(); 409 410 /// Copy data into the buffer. Size must not be greater than the number of 411 /// unused bytes in the buffer. 412 void copy_to_buffer(const char *Ptr, size_t Size); 413 414 /// Compute whether colors should be used and do the necessary work such as 415 /// flushing. The result is affected by calls to enable_color(). 416 bool prepare_colors(); 417 418 virtual void anchor(); 419 }; 420 421 /// Call the appropriate insertion operator, given an rvalue reference to a 422 /// raw_ostream object and return a stream of the same type as the argument. 423 template <typename OStream, typename T> 424 std::enable_if_t<!std::is_reference_v<OStream> && 425 std::is_base_of_v<raw_ostream, OStream>, 426 OStream &&> 427 operator<<(OStream &&OS, const T &Value) { 428 OS << Value; 429 return std::move(OS); 430 } 431 432 /// An abstract base class for streams implementations that also support a 433 /// pwrite operation. This is useful for code that can mostly stream out data, 434 /// but needs to patch in a header that needs to know the output size. 435 class LLVM_ABI raw_pwrite_stream : public raw_ostream { 436 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0; 437 void anchor() override; 438 439 public: 440 explicit raw_pwrite_stream(bool Unbuffered = false, 441 OStreamKind K = OStreamKind::OK_OStream) raw_ostream(Unbuffered,K)442 : raw_ostream(Unbuffered, K) {} pwrite(const char * Ptr,size_t Size,uint64_t Offset)443 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) { 444 #ifndef NDEBUG 445 uint64_t Pos = tell(); 446 // /dev/null always reports a pos of 0, so we cannot perform this check 447 // in that case. 448 if (Pos) 449 assert(Size + Offset <= Pos && "We don't support extending the stream"); 450 #endif 451 pwrite_impl(Ptr, Size, Offset); 452 } 453 }; 454 455 //===----------------------------------------------------------------------===// 456 // File Output Streams 457 //===----------------------------------------------------------------------===// 458 459 /// A raw_ostream that writes to a file descriptor. 460 /// 461 class LLVM_ABI raw_fd_ostream : public raw_pwrite_stream { 462 int FD; 463 bool ShouldClose; 464 bool SupportsSeeking = false; 465 bool IsRegularFile = false; 466 mutable std::optional<bool> HasColors; 467 468 /// Optional stream this stream is tied to. If this stream is written to, the 469 /// tied-to stream will be flushed first. 470 raw_ostream *TiedStream = nullptr; 471 472 #ifdef _WIN32 473 /// True if this fd refers to a Windows console device. Mintty and other 474 /// terminal emulators are TTYs, but they are not consoles. 475 bool IsWindowsConsole = false; 476 #endif 477 478 std::error_code EC; 479 480 uint64_t pos = 0; 481 482 /// See raw_ostream::write_impl. 483 void write_impl(const char *Ptr, size_t Size) override; 484 485 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 486 487 /// Return the current position within the stream, not counting the bytes 488 /// currently in the buffer. current_pos()489 uint64_t current_pos() const override { return pos; } 490 491 /// Determine an efficient buffer size. 492 size_t preferred_buffer_size() const override; 493 494 void anchor() override; 495 496 protected: 497 /// Set the flag indicating that an output error has been encountered. error_detected(std::error_code EC)498 void error_detected(std::error_code EC) { this->EC = EC; } 499 500 /// Return the file descriptor. get_fd()501 int get_fd() const { return FD; } 502 503 // Update the file position by increasing \p Delta. inc_pos(uint64_t Delta)504 void inc_pos(uint64_t Delta) { pos += Delta; } 505 506 public: 507 /// Open the specified file for writing. If an error occurs, information 508 /// about the error is put into EC, and the stream should be immediately 509 /// destroyed; 510 /// \p Flags allows optional flags to control how the file will be opened. 511 /// 512 /// As a special case, if Filename is "-", then the stream will use 513 /// STDOUT_FILENO instead of opening a file. This will not close the stdout 514 /// descriptor. 515 raw_fd_ostream(StringRef Filename, std::error_code &EC); 516 raw_fd_ostream(StringRef Filename, std::error_code &EC, 517 sys::fs::CreationDisposition Disp); 518 raw_fd_ostream(StringRef Filename, std::error_code &EC, 519 sys::fs::FileAccess Access); 520 raw_fd_ostream(StringRef Filename, std::error_code &EC, 521 sys::fs::OpenFlags Flags); 522 raw_fd_ostream(StringRef Filename, std::error_code &EC, 523 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, 524 sys::fs::OpenFlags Flags); 525 526 /// FD is the file descriptor that this writes to. If ShouldClose is true, 527 /// this closes the file when the stream is destroyed. If FD is for stdout or 528 /// stderr, it will not be closed. 529 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false, 530 OStreamKind K = OStreamKind::OK_OStream); 531 532 ~raw_fd_ostream() override; 533 534 /// Manually flush the stream and close the file. Note that this does not call 535 /// fsync. 536 void close(); 537 supportsSeeking()538 bool supportsSeeking() const { return SupportsSeeking; } 539 isRegularFile()540 bool isRegularFile() const { return IsRegularFile; } 541 542 /// Flushes the stream and repositions the underlying file descriptor position 543 /// to the offset specified from the beginning of the file. 544 uint64_t seek(uint64_t off); 545 546 bool is_displayed() const override; 547 548 bool has_colors() const override; 549 550 /// Tie this stream to the specified stream. Replaces any existing tied-to 551 /// stream. Specifying a nullptr unties the stream. This is intended for to 552 /// tie errs() to outs(), so that outs() is flushed whenever something is 553 /// written to errs(), preventing weird and hard-to-test output when stderr 554 /// is redirected to stdout. tie(raw_ostream * TieTo)555 void tie(raw_ostream *TieTo) { TiedStream = TieTo; } 556 error()557 std::error_code error() const { return EC; } 558 559 /// Return the value of the flag in this raw_fd_ostream indicating whether an 560 /// output error has been encountered. 561 /// This doesn't implicitly flush any pending output. Also, it doesn't 562 /// guarantee to detect all errors unless the stream has been closed. has_error()563 bool has_error() const { return bool(EC); } 564 565 /// Set the flag read by has_error() to false. If the error flag is set at the 566 /// time when this raw_ostream's destructor is called, report_fatal_error is 567 /// called to report the error. Use clear_error() after handling the error to 568 /// avoid this behavior. 569 /// 570 /// "Errors should never pass silently. 571 /// Unless explicitly silenced." 572 /// - from The Zen of Python, by Tim Peters 573 /// clear_error()574 void clear_error() { EC = std::error_code(); } 575 576 /// Locks the underlying file. 577 /// 578 /// @returns RAII object that releases the lock upon leaving the scope, if the 579 /// locking was successful. Otherwise returns corresponding 580 /// error code. 581 /// 582 /// The function blocks the current thread until the lock become available or 583 /// error occurs. 584 /// 585 /// Possible use of this function may be as follows: 586 /// 587 /// @code{.cpp} 588 /// if (auto L = stream.lock()) { 589 /// // ... do action that require file to be locked. 590 /// } else { 591 /// handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) { 592 /// // ... handle lock error. 593 /// }); 594 /// } 595 /// @endcode 596 [[nodiscard]] Expected<sys::fs::FileLocker> lock(); 597 598 /// Tries to lock the underlying file within the specified period. 599 /// 600 /// @returns RAII object that releases the lock upon leaving the scope, if the 601 /// locking was successful. Otherwise returns corresponding 602 /// error code. 603 /// 604 /// It is used as @ref lock. 605 [[nodiscard]] Expected<sys::fs::FileLocker> 606 tryLockFor(Duration const &Timeout); 607 }; 608 609 /// This returns a reference to a raw_fd_ostream for standard output. Use it 610 /// like: outs() << "foo" << "bar"; 611 LLVM_ABI raw_fd_ostream &outs(); 612 613 /// This returns a reference to a raw_ostream for standard error. 614 /// Use it like: errs() << "foo" << "bar"; 615 /// By default, the stream is tied to stdout to ensure stdout is flushed before 616 /// stderr is written, to ensure the error messages are written in their 617 /// expected place. 618 LLVM_ABI raw_fd_ostream &errs(); 619 620 /// This returns a reference to a raw_ostream which simply discards output. 621 LLVM_ABI raw_ostream &nulls(); 622 623 //===----------------------------------------------------------------------===// 624 // File Streams 625 //===----------------------------------------------------------------------===// 626 627 /// A raw_ostream of a file for reading/writing/seeking. 628 /// 629 class raw_fd_stream : public raw_fd_ostream { 630 public: 631 /// Open the specified file for reading/writing/seeking. If an error occurs, 632 /// information about the error is put into EC, and the stream should be 633 /// immediately destroyed. 634 LLVM_ABI raw_fd_stream(StringRef Filename, std::error_code &EC); 635 636 LLVM_ABI raw_fd_stream(int fd, bool shouldClose); 637 638 /// This reads the \p Size bytes into a buffer pointed by \p Ptr. 639 /// 640 /// \param Ptr The start of the buffer to hold data to be read. 641 /// 642 /// \param Size The number of bytes to be read. 643 /// 644 /// On success, the number of bytes read is returned, and the file position is 645 /// advanced by this number. On error, -1 is returned, use error() to get the 646 /// error code. 647 LLVM_ABI ssize_t read(char *Ptr, size_t Size); 648 649 /// Check if \p OS is a pointer of type raw_fd_stream*. 650 LLVM_ABI static bool classof(const raw_ostream *OS); 651 }; 652 653 //===----------------------------------------------------------------------===// 654 // Output Stream Adaptors 655 //===----------------------------------------------------------------------===// 656 657 /// A raw_ostream that writes to an std::string. This is a simple adaptor 658 /// class. This class does not encounter output errors. 659 /// raw_string_ostream operates without a buffer, delegating all memory 660 /// management to the std::string. Thus the std::string is always up-to-date, 661 /// may be used directly and there is no need to call flush(). 662 class LLVM_ABI raw_string_ostream : public raw_ostream { 663 std::string &OS; 664 665 /// See raw_ostream::write_impl. 666 void write_impl(const char *Ptr, size_t Size) override; 667 668 /// Return the current position within the stream, not counting the bytes 669 /// currently in the buffer. current_pos()670 uint64_t current_pos() const override { return OS.size(); } 671 672 public: raw_string_ostream(std::string & O)673 explicit raw_string_ostream(std::string &O) : OS(O) { 674 SetUnbuffered(); 675 } 676 677 /// Returns the string's reference. In most cases it is better to simply use 678 /// the underlying std::string directly. 679 /// TODO: Consider removing this API. str()680 std::string &str() { return OS; } 681 reserveExtraSpace(uint64_t ExtraSize)682 void reserveExtraSpace(uint64_t ExtraSize) override { 683 OS.reserve(tell() + ExtraSize); 684 } 685 }; 686 687 /// A raw_ostream that writes to an SmallVector or SmallString. This is a 688 /// simple adaptor class. This class does not encounter output errors. 689 /// raw_svector_ostream operates without a buffer, delegating all memory 690 /// management to the SmallString. Thus the SmallString is always up-to-date, 691 /// may be used directly and there is no need to call flush(). 692 class LLVM_ABI raw_svector_ostream : public raw_pwrite_stream { 693 SmallVectorImpl<char> &OS; 694 695 /// See raw_ostream::write_impl. 696 void write_impl(const char *Ptr, size_t Size) override; 697 698 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 699 700 /// Return the current position within the stream. 701 uint64_t current_pos() const override; 702 703 public: 704 /// Construct a new raw_svector_ostream. 705 /// 706 /// \param O The vector to write to; this should generally have at least 128 707 /// bytes free to avoid any extraneous memory overhead. raw_svector_ostream(SmallVectorImpl<char> & O)708 explicit raw_svector_ostream(SmallVectorImpl<char> &O) 709 : raw_pwrite_stream(false, raw_ostream::OStreamKind::OK_SVecStream), 710 OS(O) { 711 // FIXME: here and in a few other places, set directly to unbuffered in the 712 // ctor. 713 SetUnbuffered(); 714 } 715 716 ~raw_svector_ostream() override = default; 717 718 void flush() = delete; 719 720 /// Return a StringRef for the vector contents. str()721 StringRef str() const { return StringRef(OS.data(), OS.size()); } buffer()722 SmallVectorImpl<char> &buffer() { return OS; } 723 reserveExtraSpace(uint64_t ExtraSize)724 void reserveExtraSpace(uint64_t ExtraSize) override { 725 OS.reserve(tell() + ExtraSize); 726 } 727 728 static bool classof(const raw_ostream *OS); 729 }; 730 731 /// A raw_ostream that discards all output. 732 class LLVM_ABI raw_null_ostream : public raw_pwrite_stream { 733 /// See raw_ostream::write_impl. 734 void write_impl(const char *Ptr, size_t size) override; 735 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; 736 737 /// Return the current position within the stream, not counting the bytes 738 /// currently in the buffer. 739 uint64_t current_pos() const override; 740 741 public: 742 explicit raw_null_ostream() = default; 743 ~raw_null_ostream() override; 744 }; 745 746 class LLVM_ABI buffer_ostream : public raw_svector_ostream { 747 raw_ostream &OS; 748 SmallVector<char, 0> Buffer; 749 750 void anchor() override; 751 752 public: buffer_ostream(raw_ostream & OS)753 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {} ~buffer_ostream()754 ~buffer_ostream() override { OS << str(); } 755 }; 756 757 class LLVM_ABI buffer_unique_ostream : public raw_svector_ostream { 758 std::unique_ptr<raw_ostream> OS; 759 SmallVector<char, 0> Buffer; 760 761 void anchor() override; 762 763 public: buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)764 buffer_unique_ostream(std::unique_ptr<raw_ostream> OS) 765 : raw_svector_ostream(Buffer), OS(std::move(OS)) { 766 // Turn off buffering on OS, which we now own, to avoid allocating a buffer 767 // when the destructor writes only to be immediately flushed again. 768 this->OS->SetUnbuffered(); 769 } ~buffer_unique_ostream()770 ~buffer_unique_ostream() override { *OS << str(); } 771 }; 772 773 // Helper struct to add indentation to raw_ostream. Instead of 774 // OS.indent(6) << "more stuff"; 775 // you can use 776 // OS << indent(6) << "more stuff"; 777 // which has better ergonomics (and clang-formats better as well). 778 // 779 // If indentation is always in increments of a fixed value, you can use Scale 780 // to set that value once. So indent(1, 2) will add 2 spaces and 781 // indent(1,2) + 1 will add 4 spaces. 782 struct indent { 783 // Indentation is represented as `NumIndents` steps of size `Scale` each. 784 unsigned NumIndents; 785 unsigned Scale; 786 787 explicit indent(unsigned NumIndents, unsigned Scale = 1) NumIndentsindent788 : NumIndents(NumIndents), Scale(Scale) {} 789 790 // These arithmeric operators preserve scale. 791 void operator+=(unsigned N) { NumIndents += N; } 792 void operator-=(unsigned N) { 793 assert(NumIndents >= N && "Indentation underflow"); 794 NumIndents -= N; 795 } 796 indent operator+(unsigned N) const { return indent(NumIndents + N, Scale); } 797 indent operator-(unsigned N) const { 798 assert(NumIndents >= N && "Indentation undeflow"); 799 return indent(NumIndents - N, Scale); 800 } 801 indent &operator++() { // Prefix ++. 802 ++NumIndents; 803 return *this; 804 } 805 indent operator++(int) { // Postfix ++. 806 indent Old = *this; 807 ++NumIndents; 808 return Old; 809 } 810 indent &operator--() { // Prefix --. 811 assert(NumIndents >= 1); 812 --NumIndents; 813 return *this; 814 } 815 indent operator--(int) { // Postfix --. 816 indent Old = *this; 817 assert(NumIndents >= 1); 818 --NumIndents; 819 return Old; 820 } 821 indent &operator=(unsigned N) { 822 NumIndents = N; 823 return *this; 824 } 825 }; 826 827 inline raw_ostream &operator<<(raw_ostream &OS, const indent &Indent) { 828 return OS.indent(Indent.NumIndents * Indent.Scale); 829 } 830 831 class Error; 832 833 /// This helper creates an output stream and then passes it to \p Write. 834 /// The stream created is based on the specified \p OutputFileName: 835 /// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream 836 /// for other names. For raw_fd_ostream instances, the stream writes to 837 /// a temporary file. The final output file is atomically replaced with the 838 /// temporary file after the \p Write function is finished. 839 LLVM_ABI Error writeToOutput(StringRef OutputFileName, 840 std::function<Error(raw_ostream &)> Write); 841 842 LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t); 843 844 template <typename T, typename = decltype(std::declval<raw_ostream &>() 845 << std::declval<const T &>())> 846 raw_ostream &operator<<(raw_ostream &OS, const std::optional<T> &O) { 847 if (O) 848 OS << *O; 849 else 850 OS << std::nullopt; 851 return OS; 852 } 853 854 } // end namespace llvm 855 856 #endif // LLVM_SUPPORT_RAW_OSTREAM_H 857