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