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