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