Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:33

0001 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 //  This file defines the raw_ostream class.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
0014 #define LLVM_SUPPORT_RAW_OSTREAM_H
0015 
0016 #include "llvm/ADT/SmallVector.h"
0017 #include "llvm/ADT/StringRef.h"
0018 #include "llvm/Support/DataTypes.h"
0019 #include <cassert>
0020 #include <cstddef>
0021 #include <cstdint>
0022 #include <cstring>
0023 #include <optional>
0024 #include <string>
0025 #include <string_view>
0026 #include <system_error>
0027 #include <type_traits>
0028 
0029 namespace llvm {
0030 
0031 class Duration;
0032 class formatv_object_base;
0033 class format_object_base;
0034 class FormattedString;
0035 class FormattedNumber;
0036 class FormattedBytes;
0037 template <class T> class [[nodiscard]] Expected;
0038 
0039 namespace sys {
0040 namespace fs {
0041 enum FileAccess : unsigned;
0042 enum OpenFlags : unsigned;
0043 enum CreationDisposition : unsigned;
0044 class FileLocker;
0045 } // end namespace fs
0046 } // end namespace sys
0047 
0048 /// This class implements an extremely fast bulk output stream that can *only*
0049 /// output to a stream.  It does not support seeking, reopening, rewinding, line
0050 /// buffered disciplines etc. It is a simple buffer that outputs
0051 /// a chunk at a time.
0052 class raw_ostream {
0053 public:
0054   // Class kinds to support LLVM-style RTTI.
0055   enum class OStreamKind {
0056     OK_OStream,
0057     OK_FDStream,
0058     OK_SVecStream,
0059   };
0060 
0061 private:
0062   OStreamKind Kind;
0063 
0064   /// The buffer is handled in such a way that the buffer is
0065   /// uninitialized, unbuffered, or out of space when OutBufCur >=
0066   /// OutBufEnd. Thus a single comparison suffices to determine if we
0067   /// need to take the slow path to write a single character.
0068   ///
0069   /// The buffer is in one of three states:
0070   ///  1. Unbuffered (BufferMode == Unbuffered)
0071   ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
0072   ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
0073   ///               OutBufEnd - OutBufStart >= 1).
0074   ///
0075   /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
0076   /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
0077   /// managed by the subclass.
0078   ///
0079   /// If a subclass installs an external buffer using SetBuffer then it can wait
0080   /// for a \see write_impl() call to handle the data which has been put into
0081   /// this buffer.
0082   char *OutBufStart, *OutBufEnd, *OutBufCur;
0083   bool ColorEnabled = false;
0084 
0085   enum class BufferKind {
0086     Unbuffered = 0,
0087     InternalBuffer,
0088     ExternalBuffer
0089   } BufferMode;
0090 
0091 public:
0092   // color order matches ANSI escape sequence, don't change
0093   enum class Colors {
0094     BLACK = 0,
0095     RED,
0096     GREEN,
0097     YELLOW,
0098     BLUE,
0099     MAGENTA,
0100     CYAN,
0101     WHITE,
0102     BRIGHT_BLACK,
0103     BRIGHT_RED,
0104     BRIGHT_GREEN,
0105     BRIGHT_YELLOW,
0106     BRIGHT_BLUE,
0107     BRIGHT_MAGENTA,
0108     BRIGHT_CYAN,
0109     BRIGHT_WHITE,
0110     SAVEDCOLOR,
0111     RESET,
0112   };
0113 
0114   static constexpr Colors BLACK = Colors::BLACK;
0115   static constexpr Colors RED = Colors::RED;
0116   static constexpr Colors GREEN = Colors::GREEN;
0117   static constexpr Colors YELLOW = Colors::YELLOW;
0118   static constexpr Colors BLUE = Colors::BLUE;
0119   static constexpr Colors MAGENTA = Colors::MAGENTA;
0120   static constexpr Colors CYAN = Colors::CYAN;
0121   static constexpr Colors WHITE = Colors::WHITE;
0122   static constexpr Colors BRIGHT_BLACK = Colors::BRIGHT_BLACK;
0123   static constexpr Colors BRIGHT_RED = Colors::BRIGHT_RED;
0124   static constexpr Colors BRIGHT_GREEN = Colors::BRIGHT_GREEN;
0125   static constexpr Colors BRIGHT_YELLOW = Colors::BRIGHT_YELLOW;
0126   static constexpr Colors BRIGHT_BLUE = Colors::BRIGHT_BLUE;
0127   static constexpr Colors BRIGHT_MAGENTA = Colors::BRIGHT_MAGENTA;
0128   static constexpr Colors BRIGHT_CYAN = Colors::BRIGHT_CYAN;
0129   static constexpr Colors BRIGHT_WHITE = Colors::BRIGHT_WHITE;
0130   static constexpr Colors SAVEDCOLOR = Colors::SAVEDCOLOR;
0131   static constexpr Colors RESET = Colors::RESET;
0132 
0133   explicit raw_ostream(bool unbuffered = false,
0134                        OStreamKind K = OStreamKind::OK_OStream)
0135       : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered
0136                                        : BufferKind::InternalBuffer) {
0137     // Start out ready to flush.
0138     OutBufStart = OutBufEnd = OutBufCur = nullptr;
0139   }
0140 
0141   raw_ostream(const raw_ostream &) = delete;
0142   void operator=(const raw_ostream &) = delete;
0143 
0144   virtual ~raw_ostream();
0145 
0146   /// tell - Return the current offset with the file.
0147   uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
0148 
0149   OStreamKind get_kind() const { return Kind; }
0150 
0151   //===--------------------------------------------------------------------===//
0152   // Configuration Interface
0153   //===--------------------------------------------------------------------===//
0154 
0155   /// If possible, pre-allocate \p ExtraSize bytes for stream data.
0156   /// i.e. it extends internal buffers to keep additional ExtraSize bytes.
0157   /// So that the stream could keep at least tell() + ExtraSize bytes
0158   /// without re-allocations. reserveExtraSpace() does not change
0159   /// the size/data of the stream.
0160   virtual void reserveExtraSpace(uint64_t ExtraSize) { (void)ExtraSize; }
0161 
0162   /// Set the stream to be buffered, with an automatically determined buffer
0163   /// size.
0164   void SetBuffered();
0165 
0166   /// Set the stream to be buffered, using the specified buffer size.
0167   void SetBufferSize(size_t Size) {
0168     flush();
0169     SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
0170   }
0171 
0172   size_t GetBufferSize() const {
0173     // If we're supposed to be buffered but haven't actually gotten around
0174     // to allocating the buffer yet, return the value that would be used.
0175     if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
0176       return preferred_buffer_size();
0177 
0178     // Otherwise just return the size of the allocated buffer.
0179     return OutBufEnd - OutBufStart;
0180   }
0181 
0182   /// Set the stream to be unbuffered. When unbuffered, the stream will flush
0183   /// after every write. This routine will also flush the buffer immediately
0184   /// when the stream is being set to unbuffered.
0185   void SetUnbuffered() {
0186     flush();
0187     SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
0188   }
0189 
0190   size_t GetNumBytesInBuffer() const {
0191     return OutBufCur - OutBufStart;
0192   }
0193 
0194   //===--------------------------------------------------------------------===//
0195   // Data Output Interface
0196   //===--------------------------------------------------------------------===//
0197 
0198   void flush() {
0199     if (OutBufCur != OutBufStart)
0200       flush_nonempty();
0201   }
0202 
0203   raw_ostream &operator<<(char C) {
0204     if (OutBufCur >= OutBufEnd)
0205       return write(C);
0206     *OutBufCur++ = C;
0207     return *this;
0208   }
0209 
0210   raw_ostream &operator<<(unsigned char C) {
0211     if (OutBufCur >= OutBufEnd)
0212       return write(C);
0213     *OutBufCur++ = C;
0214     return *this;
0215   }
0216 
0217   raw_ostream &operator<<(signed char C) {
0218     if (OutBufCur >= OutBufEnd)
0219       return write(C);
0220     *OutBufCur++ = C;
0221     return *this;
0222   }
0223 
0224   raw_ostream &operator<<(StringRef Str) {
0225     // Inline fast path, particularly for strings with a known length.
0226     size_t Size = Str.size();
0227 
0228     // Make sure we can use the fast path.
0229     if (Size > (size_t)(OutBufEnd - OutBufCur))
0230       return write(Str.data(), Size);
0231 
0232     if (Size) {
0233       memcpy(OutBufCur, Str.data(), Size);
0234       OutBufCur += Size;
0235     }
0236     return *this;
0237   }
0238 
0239 #if defined(__cpp_char8_t)
0240   // When using `char8_t *` integers or pointers are written to the ostream
0241   // instead of UTF-8 code as one might expect. This might lead to unexpected
0242   // behavior, especially as `u8""` literals are of type `char8_t*` instead of
0243   // type `char_t*` from C++20 onwards. Thus we disallow using them with
0244   // raw_ostreams.
0245   // If you have u8"" literals to stream, you can rewrite them as ordinary
0246   // literals with escape sequences
0247   // e.g.  replace `u8"\u00a0"` by `"\xc2\xa0"`
0248   // or use `reinterpret_cast`:
0249   // e.g. replace `u8"\u00a0"` by `reinterpret_cast<const char *>(u8"\u00a0")`
0250   raw_ostream &operator<<(const char8_t *Str) = delete;
0251 #endif
0252 
0253   raw_ostream &operator<<(const char *Str) {
0254     // Inline fast path, particularly for constant strings where a sufficiently
0255     // smart compiler will simplify strlen.
0256 
0257     return this->operator<<(StringRef(Str));
0258   }
0259 
0260   raw_ostream &operator<<(const std::string &Str) {
0261     // Avoid the fast path, it would only increase code size for a marginal win.
0262     return write(Str.data(), Str.length());
0263   }
0264 
0265   raw_ostream &operator<<(const std::string_view &Str) {
0266     return write(Str.data(), Str.length());
0267   }
0268 
0269   raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
0270     return write(Str.data(), Str.size());
0271   }
0272 
0273   raw_ostream &operator<<(unsigned long N);
0274   raw_ostream &operator<<(long N);
0275   raw_ostream &operator<<(unsigned long long N);
0276   raw_ostream &operator<<(long long N);
0277   raw_ostream &operator<<(const void *P);
0278 
0279   raw_ostream &operator<<(unsigned int N) {
0280     return this->operator<<(static_cast<unsigned long>(N));
0281   }
0282 
0283   raw_ostream &operator<<(int N) {
0284     return this->operator<<(static_cast<long>(N));
0285   }
0286 
0287   raw_ostream &operator<<(double N);
0288 
0289   /// Output \p N in hexadecimal, without any prefix or padding.
0290   raw_ostream &write_hex(unsigned long long N);
0291 
0292   // Change the foreground color of text.
0293   raw_ostream &operator<<(Colors C);
0294 
0295   /// Output a formatted UUID with dash separators.
0296   using uuid_t = uint8_t[16];
0297   raw_ostream &write_uuid(const uuid_t UUID);
0298 
0299   /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
0300   /// satisfy llvm::isPrint into an escape sequence.
0301   raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
0302 
0303   raw_ostream &write(unsigned char C);
0304   raw_ostream &write(const char *Ptr, size_t Size);
0305 
0306   // Formatted output, see the format() function in Support/Format.h.
0307   raw_ostream &operator<<(const format_object_base &Fmt);
0308 
0309   // Formatted output, see the leftJustify() function in Support/Format.h.
0310   raw_ostream &operator<<(const FormattedString &);
0311 
0312   // Formatted output, see the formatHex() function in Support/Format.h.
0313   raw_ostream &operator<<(const FormattedNumber &);
0314 
0315   // Formatted output, see the formatv() function in Support/FormatVariadic.h.
0316   raw_ostream &operator<<(const formatv_object_base &);
0317 
0318   // Formatted output, see the format_bytes() function in Support/Format.h.
0319   raw_ostream &operator<<(const FormattedBytes &);
0320 
0321   /// indent - Insert 'NumSpaces' spaces.
0322   raw_ostream &indent(unsigned NumSpaces);
0323 
0324   /// write_zeros - Insert 'NumZeros' nulls.
0325   raw_ostream &write_zeros(unsigned NumZeros);
0326 
0327   /// Changes the foreground color of text that will be output from this point
0328   /// forward.
0329   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
0330   /// change only the bold attribute, and keep colors untouched
0331   /// @param Bold bold/brighter text, default false
0332   /// @param BG if true change the background, default: change foreground
0333   /// @returns itself so it can be used within << invocations
0334   virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false,
0335                                    bool BG = false);
0336 
0337   /// Resets the colors to terminal defaults. Call this when you are done
0338   /// outputting colored text, or before program exit.
0339   virtual raw_ostream &resetColor();
0340 
0341   /// Reverses the foreground and background colors.
0342   virtual raw_ostream &reverseColor();
0343 
0344   /// This function determines if this stream is connected to a "tty" or
0345   /// "console" window. That is, the output would be displayed to the user
0346   /// rather than being put on a pipe or stored in a file.
0347   virtual bool is_displayed() const { return false; }
0348 
0349   /// This function determines if this stream is displayed and supports colors.
0350   /// The result is unaffected by calls to enable_color().
0351   virtual bool has_colors() const { return is_displayed(); }
0352 
0353   // Enable or disable colors. Once enable_colors(false) is called,
0354   // changeColor() has no effect until enable_colors(true) is called.
0355   virtual void enable_colors(bool enable) { ColorEnabled = enable; }
0356 
0357   bool colors_enabled() const { return ColorEnabled; }
0358 
0359   //===--------------------------------------------------------------------===//
0360   // Subclass Interface
0361   //===--------------------------------------------------------------------===//
0362 
0363 private:
0364   /// The is the piece of the class that is implemented by subclasses.  This
0365   /// writes the \p Size bytes starting at
0366   /// \p Ptr to the underlying stream.
0367   ///
0368   /// This function is guaranteed to only be called at a point at which it is
0369   /// safe for the subclass to install a new buffer via SetBuffer.
0370   ///
0371   /// \param Ptr The start of the data to be written. For buffered streams this
0372   /// is guaranteed to be the start of the buffer.
0373   ///
0374   /// \param Size The number of bytes to be written.
0375   ///
0376   /// \invariant { Size > 0 }
0377   virtual void write_impl(const char *Ptr, size_t Size) = 0;
0378 
0379   /// Return the current position within the stream, not counting the bytes
0380   /// currently in the buffer.
0381   virtual uint64_t current_pos() const = 0;
0382 
0383 protected:
0384   /// Use the provided buffer as the raw_ostream buffer. This is intended for
0385   /// use only by subclasses which can arrange for the output to go directly
0386   /// into the desired output buffer, instead of being copied on each flush.
0387   void SetBuffer(char *BufferStart, size_t Size) {
0388     SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
0389   }
0390 
0391   /// Return an efficient buffer size for the underlying output mechanism.
0392   virtual size_t preferred_buffer_size() const;
0393 
0394   /// Return the beginning of the current stream buffer, or 0 if the stream is
0395   /// unbuffered.
0396   const char *getBufferStart() const { return OutBufStart; }
0397 
0398   //===--------------------------------------------------------------------===//
0399   // Private Interface
0400   //===--------------------------------------------------------------------===//
0401 private:
0402   /// Install the given buffer and mode.
0403   void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
0404 
0405   /// Flush the current buffer, which is known to be non-empty. This outputs the
0406   /// currently buffered data and resets the buffer to empty.
0407   void flush_nonempty();
0408 
0409   /// Copy data into the buffer. Size must not be greater than the number of
0410   /// unused bytes in the buffer.
0411   void copy_to_buffer(const char *Ptr, size_t Size);
0412 
0413   /// Compute whether colors should be used and do the necessary work such as
0414   /// flushing. The result is affected by calls to enable_color().
0415   bool prepare_colors();
0416 
0417   virtual void anchor();
0418 };
0419 
0420 /// Call the appropriate insertion operator, given an rvalue reference to a
0421 /// raw_ostream object and return a stream of the same type as the argument.
0422 template <typename OStream, typename T>
0423 std::enable_if_t<!std::is_reference_v<OStream> &&
0424                      std::is_base_of_v<raw_ostream, OStream>,
0425                  OStream &&>
0426 operator<<(OStream &&OS, const T &Value) {
0427   OS << Value;
0428   return std::move(OS);
0429 }
0430 
0431 /// An abstract base class for streams implementations that also support a
0432 /// pwrite operation. This is useful for code that can mostly stream out data,
0433 /// but needs to patch in a header that needs to know the output size.
0434 class raw_pwrite_stream : public raw_ostream {
0435   virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
0436   void anchor() override;
0437 
0438 public:
0439   explicit raw_pwrite_stream(bool Unbuffered = false,
0440                              OStreamKind K = OStreamKind::OK_OStream)
0441       : raw_ostream(Unbuffered, K) {}
0442   void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
0443 #ifndef NDEBUG
0444     uint64_t Pos = tell();
0445     // /dev/null always reports a pos of 0, so we cannot perform this check
0446     // in that case.
0447     if (Pos)
0448       assert(Size + Offset <= Pos && "We don't support extending the stream");
0449 #endif
0450     pwrite_impl(Ptr, Size, Offset);
0451   }
0452 };
0453 
0454 //===----------------------------------------------------------------------===//
0455 // File Output Streams
0456 //===----------------------------------------------------------------------===//
0457 
0458 /// A raw_ostream that writes to a file descriptor.
0459 ///
0460 class raw_fd_ostream : public raw_pwrite_stream {
0461   int FD;
0462   bool ShouldClose;
0463   bool SupportsSeeking = false;
0464   bool IsRegularFile = false;
0465   mutable std::optional<bool> HasColors;
0466 
0467   /// Optional stream this stream is tied to. If this stream is written to, the
0468   /// tied-to stream will be flushed first.
0469   raw_ostream *TiedStream = nullptr;
0470 
0471 #ifdef _WIN32
0472   /// True if this fd refers to a Windows console device. Mintty and other
0473   /// terminal emulators are TTYs, but they are not consoles.
0474   bool IsWindowsConsole = false;
0475 #endif
0476 
0477   std::error_code EC;
0478 
0479   uint64_t pos = 0;
0480 
0481   /// See raw_ostream::write_impl.
0482   void write_impl(const char *Ptr, size_t Size) override;
0483 
0484   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
0485 
0486   /// Return the current position within the stream, not counting the bytes
0487   /// currently in the buffer.
0488   uint64_t current_pos() const override { return pos; }
0489 
0490   /// Determine an efficient buffer size.
0491   size_t preferred_buffer_size() const override;
0492 
0493   void anchor() override;
0494 
0495 protected:
0496   /// Set the flag indicating that an output error has been encountered.
0497   void error_detected(std::error_code EC) { this->EC = EC; }
0498 
0499   /// Return the file descriptor.
0500   int get_fd() const { return FD; }
0501 
0502   // Update the file position by increasing \p Delta.
0503   void inc_pos(uint64_t Delta) { pos += Delta; }
0504 
0505 public:
0506   /// Open the specified file for writing. If an error occurs, information
0507   /// about the error is put into EC, and the stream should be immediately
0508   /// destroyed;
0509   /// \p Flags allows optional flags to control how the file will be opened.
0510   ///
0511   /// As a special case, if Filename is "-", then the stream will use
0512   /// STDOUT_FILENO instead of opening a file. This will not close the stdout
0513   /// descriptor.
0514   raw_fd_ostream(StringRef Filename, std::error_code &EC);
0515   raw_fd_ostream(StringRef Filename, std::error_code &EC,
0516                  sys::fs::CreationDisposition Disp);
0517   raw_fd_ostream(StringRef Filename, std::error_code &EC,
0518                  sys::fs::FileAccess Access);
0519   raw_fd_ostream(StringRef Filename, std::error_code &EC,
0520                  sys::fs::OpenFlags Flags);
0521   raw_fd_ostream(StringRef Filename, std::error_code &EC,
0522                  sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
0523                  sys::fs::OpenFlags Flags);
0524 
0525   /// FD is the file descriptor that this writes to.  If ShouldClose is true,
0526   /// this closes the file when the stream is destroyed. If FD is for stdout or
0527   /// stderr, it will not be closed.
0528   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
0529                  OStreamKind K = OStreamKind::OK_OStream);
0530 
0531   ~raw_fd_ostream() override;
0532 
0533   /// Manually flush the stream and close the file. Note that this does not call
0534   /// fsync.
0535   void close();
0536 
0537   bool supportsSeeking() const { return SupportsSeeking; }
0538 
0539   bool isRegularFile() const { return IsRegularFile; }
0540 
0541   /// Flushes the stream and repositions the underlying file descriptor position
0542   /// to the offset specified from the beginning of the file.
0543   uint64_t seek(uint64_t off);
0544 
0545   bool is_displayed() const override;
0546 
0547   bool has_colors() const override;
0548 
0549   /// Tie this stream to the specified stream. Replaces any existing tied-to
0550   /// stream. Specifying a nullptr unties the stream. This is intended for to
0551   /// tie errs() to outs(), so that outs() is flushed whenever something is
0552   /// written to errs(), preventing weird and hard-to-test output when stderr
0553   /// is redirected to stdout.
0554   void tie(raw_ostream *TieTo) { TiedStream = TieTo; }
0555 
0556   std::error_code error() const { return EC; }
0557 
0558   /// Return the value of the flag in this raw_fd_ostream indicating whether an
0559   /// output error has been encountered.
0560   /// This doesn't implicitly flush any pending output.  Also, it doesn't
0561   /// guarantee to detect all errors unless the stream has been closed.
0562   bool has_error() const { return bool(EC); }
0563 
0564   /// Set the flag read by has_error() to false. If the error flag is set at the
0565   /// time when this raw_ostream's destructor is called, report_fatal_error is
0566   /// called to report the error. Use clear_error() after handling the error to
0567   /// avoid this behavior.
0568   ///
0569   ///   "Errors should never pass silently.
0570   ///    Unless explicitly silenced."
0571   ///      - from The Zen of Python, by Tim Peters
0572   ///
0573   void clear_error() { EC = std::error_code(); }
0574 
0575   /// Locks the underlying file.
0576   ///
0577   /// @returns RAII object that releases the lock upon leaving the scope, if the
0578   ///          locking was successful. Otherwise returns corresponding
0579   ///          error code.
0580   ///
0581   /// The function blocks the current thread until the lock become available or
0582   /// error occurs.
0583   ///
0584   /// Possible use of this function may be as follows:
0585   ///
0586   ///   @code{.cpp}
0587   ///   if (auto L = stream.lock()) {
0588   ///     // ... do action that require file to be locked.
0589   ///   } else {
0590   ///     handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) {
0591   ///       // ... handle lock error.
0592   ///     });
0593   ///   }
0594   ///   @endcode
0595   [[nodiscard]] Expected<sys::fs::FileLocker> lock();
0596 
0597   /// Tries to lock the underlying file within the specified period.
0598   ///
0599   /// @returns RAII object that releases the lock upon leaving the scope, if the
0600   ///          locking was successful. Otherwise returns corresponding
0601   ///          error code.
0602   ///
0603   /// It is used as @ref lock.
0604   [[nodiscard]] Expected<sys::fs::FileLocker>
0605   tryLockFor(Duration const &Timeout);
0606 };
0607 
0608 /// This returns a reference to a raw_fd_ostream for standard output. Use it
0609 /// like: outs() << "foo" << "bar";
0610 raw_fd_ostream &outs();
0611 
0612 /// This returns a reference to a raw_ostream for standard error.
0613 /// Use it like: errs() << "foo" << "bar";
0614 /// By default, the stream is tied to stdout to ensure stdout is flushed before
0615 /// stderr is written, to ensure the error messages are written in their
0616 /// expected place.
0617 raw_fd_ostream &errs();
0618 
0619 /// This returns a reference to a raw_ostream which simply discards output.
0620 raw_ostream &nulls();
0621 
0622 //===----------------------------------------------------------------------===//
0623 // File Streams
0624 //===----------------------------------------------------------------------===//
0625 
0626 /// A raw_ostream of a file for reading/writing/seeking.
0627 ///
0628 class raw_fd_stream : public raw_fd_ostream {
0629 public:
0630   /// Open the specified file for reading/writing/seeking. If an error occurs,
0631   /// information about the error is put into EC, and the stream should be
0632   /// immediately destroyed.
0633   raw_fd_stream(StringRef Filename, std::error_code &EC);
0634 
0635   raw_fd_stream(int fd, bool shouldClose);
0636 
0637   /// This reads the \p Size bytes into a buffer pointed by \p Ptr.
0638   ///
0639   /// \param Ptr The start of the buffer to hold data to be read.
0640   ///
0641   /// \param Size The number of bytes to be read.
0642   ///
0643   /// On success, the number of bytes read is returned, and the file position is
0644   /// advanced by this number. On error, -1 is returned, use error() to get the
0645   /// error code.
0646   ssize_t read(char *Ptr, size_t Size);
0647 
0648   /// Check if \p OS is a pointer of type raw_fd_stream*.
0649   static bool classof(const raw_ostream *OS);
0650 };
0651 
0652 //===----------------------------------------------------------------------===//
0653 // Output Stream Adaptors
0654 //===----------------------------------------------------------------------===//
0655 
0656 /// A raw_ostream that writes to an std::string.  This is a simple adaptor
0657 /// class. This class does not encounter output errors.
0658 /// raw_string_ostream operates without a buffer, delegating all memory
0659 /// management to the std::string. Thus the std::string is always up-to-date,
0660 /// may be used directly and there is no need to call flush().
0661 class raw_string_ostream : public raw_ostream {
0662   std::string &OS;
0663 
0664   /// See raw_ostream::write_impl.
0665   void write_impl(const char *Ptr, size_t Size) override;
0666 
0667   /// Return the current position within the stream, not counting the bytes
0668   /// currently in the buffer.
0669   uint64_t current_pos() const override { return OS.size(); }
0670 
0671 public:
0672   explicit raw_string_ostream(std::string &O) : OS(O) {
0673     SetUnbuffered();
0674   }
0675 
0676   /// Returns the string's reference. In most cases it is better to simply use
0677   /// the underlying std::string directly.
0678   /// TODO: Consider removing this API.
0679   std::string &str() { return OS; }
0680 
0681   void reserveExtraSpace(uint64_t ExtraSize) override {
0682     OS.reserve(tell() + ExtraSize);
0683   }
0684 };
0685 
0686 /// A raw_ostream that writes to an SmallVector or SmallString.  This is a
0687 /// simple adaptor class. This class does not encounter output errors.
0688 /// raw_svector_ostream operates without a buffer, delegating all memory
0689 /// management to the SmallString. Thus the SmallString is always up-to-date,
0690 /// may be used directly and there is no need to call flush().
0691 class raw_svector_ostream : public raw_pwrite_stream {
0692   SmallVectorImpl<char> &OS;
0693 
0694   /// See raw_ostream::write_impl.
0695   void write_impl(const char *Ptr, size_t Size) override;
0696 
0697   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
0698 
0699   /// Return the current position within the stream.
0700   uint64_t current_pos() const override;
0701 
0702 public:
0703   /// Construct a new raw_svector_ostream.
0704   ///
0705   /// \param O The vector to write to; this should generally have at least 128
0706   /// bytes free to avoid any extraneous memory overhead.
0707   explicit raw_svector_ostream(SmallVectorImpl<char> &O)
0708       : raw_pwrite_stream(false, raw_ostream::OStreamKind::OK_SVecStream),
0709         OS(O) {
0710     // FIXME: here and in a few other places, set directly to unbuffered in the
0711     // ctor.
0712     SetUnbuffered();
0713   }
0714 
0715   ~raw_svector_ostream() override = default;
0716 
0717   void flush() = delete;
0718 
0719   /// Return a StringRef for the vector contents.
0720   StringRef str() const { return StringRef(OS.data(), OS.size()); }
0721   SmallVectorImpl<char> &buffer() { return OS; }
0722 
0723   void reserveExtraSpace(uint64_t ExtraSize) override {
0724     OS.reserve(tell() + ExtraSize);
0725   }
0726 
0727   static bool classof(const raw_ostream *OS);
0728 };
0729 
0730 /// A raw_ostream that discards all output.
0731 class raw_null_ostream : public raw_pwrite_stream {
0732   /// See raw_ostream::write_impl.
0733   void write_impl(const char *Ptr, size_t size) override;
0734   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
0735 
0736   /// Return the current position within the stream, not counting the bytes
0737   /// currently in the buffer.
0738   uint64_t current_pos() const override;
0739 
0740 public:
0741   explicit raw_null_ostream() = default;
0742   ~raw_null_ostream() override;
0743 };
0744 
0745 class buffer_ostream : public raw_svector_ostream {
0746   raw_ostream &OS;
0747   SmallVector<char, 0> Buffer;
0748 
0749   void anchor() override;
0750 
0751 public:
0752   buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
0753   ~buffer_ostream() override { OS << str(); }
0754 };
0755 
0756 class buffer_unique_ostream : public raw_svector_ostream {
0757   std::unique_ptr<raw_ostream> OS;
0758   SmallVector<char, 0> Buffer;
0759 
0760   void anchor() override;
0761 
0762 public:
0763   buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)
0764       : raw_svector_ostream(Buffer), OS(std::move(OS)) {
0765     // Turn off buffering on OS, which we now own, to avoid allocating a buffer
0766     // when the destructor writes only to be immediately flushed again.
0767     this->OS->SetUnbuffered();
0768   }
0769   ~buffer_unique_ostream() override { *OS << str(); }
0770 };
0771 
0772 // Helper struct to add indentation to raw_ostream. Instead of
0773 // OS.indent(6) << "more stuff";
0774 // you can use
0775 // OS << indent(6) << "more stuff";
0776 // which has better ergonomics (and clang-formats better as well).
0777 //
0778 // If indentation is always in increments of a fixed value, you can use Scale
0779 // to set that value once. So indent(1, 2) will add 2 spaces and
0780 // indent(1,2) + 1 will add 4 spaces.
0781 struct indent {
0782   // Indentation is represented as `NumIndents` steps of size `Scale` each.
0783   unsigned NumIndents;
0784   unsigned Scale;
0785 
0786   explicit indent(unsigned NumIndents, unsigned Scale = 1)
0787       : NumIndents(NumIndents), Scale(Scale) {}
0788 
0789   // These arithmeric operators preserve scale.
0790   void operator+=(unsigned N) { NumIndents += N; }
0791   void operator-=(unsigned N) {
0792     assert(NumIndents >= N && "Indentation underflow");
0793     NumIndents -= N;
0794   }
0795   indent operator+(unsigned N) const { return indent(NumIndents + N, Scale); }
0796   indent operator-(unsigned N) const {
0797     assert(NumIndents >= N && "Indentation undeflow");
0798     return indent(NumIndents - N, Scale);
0799   }
0800   indent &operator++() { // Prefix ++.
0801     ++NumIndents;
0802     return *this;
0803   }
0804   indent operator++(int) { // Postfix ++.
0805     indent Old = *this;
0806     ++NumIndents;
0807     return Old;
0808   }
0809   indent &operator--() { // Prefix --.
0810     assert(NumIndents >= 1);
0811     --NumIndents;
0812     return *this;
0813   }
0814   indent operator--(int) { // Postfix --.
0815     indent Old = *this;
0816     assert(NumIndents >= 1);
0817     --NumIndents;
0818     return Old;
0819   }
0820   indent &operator=(unsigned N) {
0821     NumIndents = N;
0822     return *this;
0823   }
0824 };
0825 
0826 inline raw_ostream &operator<<(raw_ostream &OS, const indent &Indent) {
0827   return OS.indent(Indent.NumIndents * Indent.Scale);
0828 }
0829 
0830 class Error;
0831 
0832 /// This helper creates an output stream and then passes it to \p Write.
0833 /// The stream created is based on the specified \p OutputFileName:
0834 /// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream
0835 /// for other names. For raw_fd_ostream instances, the stream writes to
0836 /// a temporary file. The final output file is atomically replaced with the
0837 /// temporary file after the \p Write function is finished.
0838 Error writeToOutput(StringRef OutputFileName,
0839                     std::function<Error(raw_ostream &)> Write);
0840 
0841 raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t);
0842 
0843 template <typename T, typename = decltype(std::declval<raw_ostream &>()
0844                                           << std::declval<const T &>())>
0845 raw_ostream &operator<<(raw_ostream &OS, const std::optional<T> &O) {
0846   if (O)
0847     OS << *O;
0848   else
0849     OS << std::nullopt;
0850   return OS;
0851 }
0852 
0853 } // end namespace llvm
0854 
0855 #endif // LLVM_SUPPORT_RAW_OSTREAM_H