1193323Sed//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed//  This file defines the raw_ostream class.
10193323Sed//
11193323Sed//===----------------------------------------------------------------------===//
12193323Sed
13193323Sed#ifndef LLVM_SUPPORT_RAW_OSTREAM_H
14193323Sed#define LLVM_SUPPORT_RAW_OSTREAM_H
15193323Sed
16288943Sdim#include "llvm/ADT/SmallVector.h"
17198090Srdivacky#include "llvm/ADT/StringRef.h"
18314564Sdim#include <cassert>
19314564Sdim#include <cstddef>
20314564Sdim#include <cstdint>
21314564Sdim#include <cstring>
22314564Sdim#include <string>
23280031Sdim#include <system_error>
24360784Sdim#include <type_traits>
25193323Sed
26193323Sednamespace llvm {
27314564Sdim
28314564Sdimclass formatv_object_base;
29288943Sdimclass format_object_base;
30288943Sdimclass FormattedString;
31288943Sdimclass FormattedNumber;
32314564Sdimclass FormattedBytes;
33193323Sed
34288943Sdimnamespace sys {
35288943Sdimnamespace fs {
36341825Sdimenum FileAccess : unsigned;
37288943Sdimenum OpenFlags : unsigned;
38341825Sdimenum CreationDisposition : unsigned;
39314564Sdim} // end namespace fs
40314564Sdim} // end namespace sys
41276479Sdim
42288943Sdim/// This class implements an extremely fast bulk output stream that can *only*
43288943Sdim/// output to a stream.  It does not support seeking, reopening, rewinding, line
44288943Sdim/// buffered disciplines etc. It is a simple buffer that outputs
45193323Sed/// a chunk at a time.
46193323Sedclass raw_ostream {
47193323Sedprivate:
48193323Sed  /// The buffer is handled in such a way that the buffer is
49193323Sed  /// uninitialized, unbuffered, or out of space when OutBufCur >=
50193323Sed  /// OutBufEnd. Thus a single comparison suffices to determine if we
51193323Sed  /// need to take the slow path to write a single character.
52193323Sed  ///
53193323Sed  /// The buffer is in one of three states:
54198090Srdivacky  ///  1. Unbuffered (BufferMode == Unbuffered)
55198090Srdivacky  ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
56198090Srdivacky  ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
57198090Srdivacky  ///               OutBufEnd - OutBufStart >= 1).
58198090Srdivacky  ///
59198090Srdivacky  /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
60198090Srdivacky  /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
61198090Srdivacky  /// managed by the subclass.
62198090Srdivacky  ///
63198090Srdivacky  /// If a subclass installs an external buffer using SetBuffer then it can wait
64198090Srdivacky  /// for a \see write_impl() call to handle the data which has been put into
65198090Srdivacky  /// this buffer.
66193323Sed  char *OutBufStart, *OutBufEnd, *OutBufCur;
67198113Srdivacky
68360784Sdim  enum class BufferKind {
69198090Srdivacky    Unbuffered = 0,
70198090Srdivacky    InternalBuffer,
71198090Srdivacky    ExternalBuffer
72198090Srdivacky  } BufferMode;
73193323Sed
74193323Sedpublic:
75193574Sed  // color order matches ANSI escape sequence, don't change
76360784Sdim  enum class Colors {
77314564Sdim    BLACK = 0,
78193574Sed    RED,
79193574Sed    GREEN,
80193574Sed    YELLOW,
81193574Sed    BLUE,
82193574Sed    MAGENTA,
83193574Sed    CYAN,
84193574Sed    WHITE,
85360784Sdim    SAVEDCOLOR,
86360784Sdim    RESET,
87193574Sed  };
88193574Sed
89360784Sdim  static const Colors BLACK = Colors::BLACK;
90360784Sdim  static const Colors RED = Colors::RED;
91360784Sdim  static const Colors GREEN = Colors::GREEN;
92360784Sdim  static const Colors YELLOW = Colors::YELLOW;
93360784Sdim  static const Colors BLUE = Colors::BLUE;
94360784Sdim  static const Colors MAGENTA = Colors::MAGENTA;
95360784Sdim  static const Colors CYAN = Colors::CYAN;
96360784Sdim  static const Colors WHITE = Colors::WHITE;
97360784Sdim  static const Colors SAVEDCOLOR = Colors::SAVEDCOLOR;
98360784Sdim  static const Colors RESET = Colors::RESET;
99360784Sdim
100288943Sdim  explicit raw_ostream(bool unbuffered = false)
101360784Sdim      : BufferMode(unbuffered ? BufferKind::Unbuffered
102360784Sdim                              : BufferKind::InternalBuffer) {
103193323Sed    // Start out ready to flush.
104276479Sdim    OutBufStart = OutBufEnd = OutBufCur = nullptr;
105193323Sed  }
106193323Sed
107314564Sdim  raw_ostream(const raw_ostream &) = delete;
108314564Sdim  void operator=(const raw_ostream &) = delete;
109314564Sdim
110198090Srdivacky  virtual ~raw_ostream();
111193323Sed
112193323Sed  /// tell - Return the current offset with the file.
113201360Srdivacky  uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
114193323Sed
115193323Sed  //===--------------------------------------------------------------------===//
116193323Sed  // Configuration Interface
117193323Sed  //===--------------------------------------------------------------------===//
118193323Sed
119288943Sdim  /// Set the stream to be buffered, with an automatically determined buffer
120288943Sdim  /// size.
121198090Srdivacky  void SetBuffered();
122198090Srdivacky
123288943Sdim  /// Set the stream to be buffered, using the specified buffer size.
124198090Srdivacky  void SetBufferSize(size_t Size) {
125193323Sed    flush();
126360784Sdim    SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
127198090Srdivacky  }
128193323Sed
129201360Srdivacky  size_t GetBufferSize() const {
130198090Srdivacky    // If we're supposed to be buffered but haven't actually gotten around
131198090Srdivacky    // to allocating the buffer yet, return the value that would be used.
132360784Sdim    if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
133198090Srdivacky      return preferred_buffer_size();
134198090Srdivacky
135198090Srdivacky    // Otherwise just return the size of the allocated buffer.
136198090Srdivacky    return OutBufEnd - OutBufStart;
137193323Sed  }
138193323Sed
139288943Sdim  /// Set the stream to be unbuffered. When unbuffered, the stream will flush
140288943Sdim  /// after every write. This routine will also flush the buffer immediately
141288943Sdim  /// when the stream is being set to unbuffered.
142193323Sed  void SetUnbuffered() {
143193323Sed    flush();
144360784Sdim    SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
145193323Sed  }
146193323Sed
147198090Srdivacky  size_t GetNumBytesInBuffer() const {
148193323Sed    return OutBufCur - OutBufStart;
149193323Sed  }
150193323Sed
151193323Sed  //===--------------------------------------------------------------------===//
152193323Sed  // Data Output Interface
153193323Sed  //===--------------------------------------------------------------------===//
154193323Sed
155193323Sed  void flush() {
156193323Sed    if (OutBufCur != OutBufStart)
157193323Sed      flush_nonempty();
158193323Sed  }
159193323Sed
160193323Sed  raw_ostream &operator<<(char C) {
161193323Sed    if (OutBufCur >= OutBufEnd)
162193323Sed      return write(C);
163193323Sed    *OutBufCur++ = C;
164193323Sed    return *this;
165193323Sed  }
166193323Sed
167193323Sed  raw_ostream &operator<<(unsigned char C) {
168193323Sed    if (OutBufCur >= OutBufEnd)
169193323Sed      return write(C);
170193323Sed    *OutBufCur++ = C;
171193323Sed    return *this;
172193323Sed  }
173193323Sed
174193323Sed  raw_ostream &operator<<(signed char C) {
175193323Sed    if (OutBufCur >= OutBufEnd)
176193323Sed      return write(C);
177193323Sed    *OutBufCur++ = C;
178193323Sed    return *this;
179193323Sed  }
180193323Sed
181199481Srdivacky  raw_ostream &operator<<(StringRef Str) {
182198090Srdivacky    // Inline fast path, particularly for strings with a known length.
183198090Srdivacky    size_t Size = Str.size();
184193323Sed
185193323Sed    // Make sure we can use the fast path.
186276479Sdim    if (Size > (size_t)(OutBufEnd - OutBufCur))
187198090Srdivacky      return write(Str.data(), Size);
188193323Sed
189288943Sdim    if (Size) {
190288943Sdim      memcpy(OutBufCur, Str.data(), Size);
191288943Sdim      OutBufCur += Size;
192288943Sdim    }
193193323Sed    return *this;
194193323Sed  }
195193323Sed
196198090Srdivacky  raw_ostream &operator<<(const char *Str) {
197218893Sdim    // Inline fast path, particularly for constant strings where a sufficiently
198198090Srdivacky    // smart compiler will simplify strlen.
199198090Srdivacky
200200581Srdivacky    return this->operator<<(StringRef(Str));
201198090Srdivacky  }
202198090Srdivacky
203198090Srdivacky  raw_ostream &operator<<(const std::string &Str) {
204198090Srdivacky    // Avoid the fast path, it would only increase code size for a marginal win.
205200581Srdivacky    return write(Str.data(), Str.length());
206193323Sed  }
207193323Sed
208314564Sdim  raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
209288943Sdim    return write(Str.data(), Str.size());
210288943Sdim  }
211288943Sdim
212193323Sed  raw_ostream &operator<<(unsigned long N);
213193323Sed  raw_ostream &operator<<(long N);
214193323Sed  raw_ostream &operator<<(unsigned long long N);
215193323Sed  raw_ostream &operator<<(long long N);
216193323Sed  raw_ostream &operator<<(const void *P);
217314564Sdim
218193323Sed  raw_ostream &operator<<(unsigned int N) {
219200581Srdivacky    return this->operator<<(static_cast<unsigned long>(N));
220193323Sed  }
221193323Sed
222193323Sed  raw_ostream &operator<<(int N) {
223200581Srdivacky    return this->operator<<(static_cast<long>(N));
224193323Sed  }
225193323Sed
226198113Srdivacky  raw_ostream &operator<<(double N);
227193323Sed
228288943Sdim  /// Output \p N in hexadecimal, without any prefix or padding.
229198090Srdivacky  raw_ostream &write_hex(unsigned long long N);
230198090Srdivacky
231360784Sdim  // Change the foreground color of text.
232360784Sdim  raw_ostream &operator<<(Colors C);
233360784Sdim
234327952Sdim  /// Output a formatted UUID with dash separators.
235327952Sdim  using uuid_t = uint8_t[16];
236327952Sdim  raw_ostream &write_uuid(const uuid_t UUID);
237327952Sdim
238288943Sdim  /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
239341825Sdim  /// satisfy llvm::isPrint into an escape sequence.
240218893Sdim  raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
241198396Srdivacky
242193323Sed  raw_ostream &write(unsigned char C);
243198090Srdivacky  raw_ostream &write(const char *Ptr, size_t Size);
244193323Sed
245193323Sed  // Formatted output, see the format() function in Support/Format.h.
246193323Sed  raw_ostream &operator<<(const format_object_base &Fmt);
247193323Sed
248280031Sdim  // Formatted output, see the leftJustify() function in Support/Format.h.
249280031Sdim  raw_ostream &operator<<(const FormattedString &);
250296417Sdim
251280031Sdim  // Formatted output, see the formatHex() function in Support/Format.h.
252280031Sdim  raw_ostream &operator<<(const FormattedNumber &);
253296417Sdim
254314564Sdim  // Formatted output, see the formatv() function in Support/FormatVariadic.h.
255314564Sdim  raw_ostream &operator<<(const formatv_object_base &);
256314564Sdim
257314564Sdim  // Formatted output, see the format_bytes() function in Support/Format.h.
258314564Sdim  raw_ostream &operator<<(const FormattedBytes &);
259314564Sdim
260198090Srdivacky  /// indent - Insert 'NumSpaces' spaces.
261198090Srdivacky  raw_ostream &indent(unsigned NumSpaces);
262198113Srdivacky
263341825Sdim  /// write_zeros - Insert 'NumZeros' nulls.
264341825Sdim  raw_ostream &write_zeros(unsigned NumZeros);
265341825Sdim
266193574Sed  /// Changes the foreground color of text that will be output from this point
267193574Sed  /// forward.
268243830Sdim  /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
269193574Sed  /// change only the bold attribute, and keep colors untouched
270243830Sdim  /// @param Bold bold/brighter text, default false
271243830Sdim  /// @param BG if true change the background, default: change foreground
272193574Sed  /// @returns itself so it can be used within << invocations
273243830Sdim  virtual raw_ostream &changeColor(enum Colors Color,
274243830Sdim                                   bool Bold = false,
275243830Sdim                                   bool BG = false) {
276243830Sdim    (void)Color;
277243830Sdim    (void)Bold;
278243830Sdim    (void)BG;
279243830Sdim    return *this;
280243830Sdim  }
281193574Sed
282193574Sed  /// Resets the colors to terminal defaults. Call this when you are done
283193574Sed  /// outputting colored text, or before program exit.
284193574Sed  virtual raw_ostream &resetColor() { return *this; }
285193574Sed
286296417Sdim  /// Reverses the foreground and background colors.
287234982Sdim  virtual raw_ostream &reverseColor() { return *this; }
288234982Sdim
289198090Srdivacky  /// This function determines if this stream is connected to a "tty" or
290198090Srdivacky  /// "console" window. That is, the output would be displayed to the user
291198090Srdivacky  /// rather than being put on a pipe or stored in a file.
292198090Srdivacky  virtual bool is_displayed() const { return false; }
293198090Srdivacky
294239462Sdim  /// This function determines if this stream is displayed and supports colors.
295239462Sdim  virtual bool has_colors() const { return is_displayed(); }
296239462Sdim
297360784Sdim  // Enable or disable colors. Once disable_colors() is called,
298360784Sdim  // changeColor() has no effect until enable_colors() is called.
299360784Sdim  virtual void enable_colors(bool /*enable*/) {}
300360784Sdim
301193323Sed  //===--------------------------------------------------------------------===//
302193323Sed  // Subclass Interface
303193323Sed  //===--------------------------------------------------------------------===//
304193323Sed
305193323Sedprivate:
306288943Sdim  /// The is the piece of the class that is implemented by subclasses.  This
307288943Sdim  /// writes the \p Size bytes starting at
308243830Sdim  /// \p Ptr to the underlying stream.
309198113Srdivacky  ///
310198090Srdivacky  /// This function is guaranteed to only be called at a point at which it is
311198090Srdivacky  /// safe for the subclass to install a new buffer via SetBuffer.
312198090Srdivacky  ///
313243830Sdim  /// \param Ptr The start of the data to be written. For buffered streams this
314198090Srdivacky  /// is guaranteed to be the start of the buffer.
315198090Srdivacky  ///
316243830Sdim  /// \param Size The number of bytes to be written.
317243830Sdim  ///
318193323Sed  /// \invariant { Size > 0 }
319198090Srdivacky  virtual void write_impl(const char *Ptr, size_t Size) = 0;
320193323Sed
321288943Sdim  /// Return the current position within the stream, not counting the bytes
322288943Sdim  /// currently in the buffer.
323201360Srdivacky  virtual uint64_t current_pos() const = 0;
324193323Sed
325198090Srdivackyprotected:
326288943Sdim  /// Use the provided buffer as the raw_ostream buffer. This is intended for
327288943Sdim  /// use only by subclasses which can arrange for the output to go directly
328288943Sdim  /// into the desired output buffer, instead of being copied on each flush.
329198090Srdivacky  void SetBuffer(char *BufferStart, size_t Size) {
330360784Sdim    SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
331198090Srdivacky  }
332198090Srdivacky
333288943Sdim  /// Return an efficient buffer size for the underlying output mechanism.
334201360Srdivacky  virtual size_t preferred_buffer_size() const;
335198090Srdivacky
336288943Sdim  /// Return the beginning of the current stream buffer, or 0 if the stream is
337288943Sdim  /// unbuffered.
338198090Srdivacky  const char *getBufferStart() const { return OutBufStart; }
339198090Srdivacky
340193323Sed  //===--------------------------------------------------------------------===//
341193323Sed  // Private Interface
342193323Sed  //===--------------------------------------------------------------------===//
343193323Sedprivate:
344288943Sdim  /// Install the given buffer and mode.
345198090Srdivacky  void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
346198090Srdivacky
347288943Sdim  /// Flush the current buffer, which is known to be non-empty. This outputs the
348288943Sdim  /// currently buffered data and resets the buffer to empty.
349193323Sed  void flush_nonempty();
350198090Srdivacky
351288943Sdim  /// Copy data into the buffer. Size must not be greater than the number of
352288943Sdim  /// unused bytes in the buffer.
353198090Srdivacky  void copy_to_buffer(const char *Ptr, size_t Size);
354341825Sdim
355341825Sdim  virtual void anchor();
356193323Sed};
357193323Sed
358360784Sdim/// Call the appropriate insertion operator, given an rvalue reference to a
359360784Sdim/// raw_ostream object and return a stream of the same type as the argument.
360360784Sdimtemplate <typename OStream, typename T>
361360784Sdimtypename std::enable_if<!std::is_reference<OStream>::value &&
362360784Sdim                            std::is_base_of<raw_ostream, OStream>::value,
363360784Sdim                        OStream &&>::type
364360784Sdimoperator<<(OStream &&OS, const T &Value) {
365360784Sdim  OS << Value;
366360784Sdim  return std::move(OS);
367360784Sdim}
368360784Sdim
369288943Sdim/// An abstract base class for streams implementations that also support a
370296417Sdim/// pwrite operation. This is useful for code that can mostly stream out data,
371288943Sdim/// but needs to patch in a header that needs to know the output size.
372288943Sdimclass raw_pwrite_stream : public raw_ostream {
373288943Sdim  virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
374341825Sdim  void anchor() override;
375288943Sdim
376288943Sdimpublic:
377288943Sdim  explicit raw_pwrite_stream(bool Unbuffered = false)
378288943Sdim      : raw_ostream(Unbuffered) {}
379288943Sdim  void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
380353358Sdim#ifndef NDEBUG
381288943Sdim    uint64_t Pos = tell();
382288943Sdim    // /dev/null always reports a pos of 0, so we cannot perform this check
383288943Sdim    // in that case.
384288943Sdim    if (Pos)
385288943Sdim      assert(Size + Offset <= Pos && "We don't support extending the stream");
386288943Sdim#endif
387288943Sdim    pwrite_impl(Ptr, Size, Offset);
388288943Sdim  }
389288943Sdim};
390288943Sdim
391193323Sed//===----------------------------------------------------------------------===//
392193323Sed// File Output Streams
393193323Sed//===----------------------------------------------------------------------===//
394193323Sed
395288943Sdim/// A raw_ostream that writes to a file descriptor.
396193323Sed///
397288943Sdimclass raw_fd_ostream : public raw_pwrite_stream {
398193323Sed  int FD;
399193323Sed  bool ShouldClose;
400360784Sdim  bool SupportsSeeking = false;
401360784Sdim  bool ColorEnabled = true;
402212904Sdim
403344779Sdim#ifdef _WIN32
404344779Sdim  /// True if this fd refers to a Windows console device. Mintty and other
405344779Sdim  /// terminal emulators are TTYs, but they are not consoles.
406344779Sdim  bool IsWindowsConsole = false;
407344779Sdim#endif
408344779Sdim
409327952Sdim  std::error_code EC;
410212904Sdim
411360784Sdim  uint64_t pos = 0;
412193323Sed
413288943Sdim  /// See raw_ostream::write_impl.
414276479Sdim  void write_impl(const char *Ptr, size_t Size) override;
415193323Sed
416288943Sdim  void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
417288943Sdim
418288943Sdim  /// Return the current position within the stream, not counting the bytes
419288943Sdim  /// currently in the buffer.
420276479Sdim  uint64_t current_pos() const override { return pos; }
421193323Sed
422288943Sdim  /// Determine an efficient buffer size.
423276479Sdim  size_t preferred_buffer_size() const override;
424198090Srdivacky
425288943Sdim  /// Set the flag indicating that an output error has been encountered.
426327952Sdim  void error_detected(std::error_code EC) { this->EC = EC; }
427212904Sdim
428341825Sdim  void anchor() override;
429341825Sdim
430193323Sedpublic:
431280031Sdim  /// Open the specified file for writing. If an error occurs, information
432280031Sdim  /// about the error is put into EC, and the stream should be immediately
433280031Sdim  /// destroyed;
434280031Sdim  /// \p Flags allows optional flags to control how the file will be opened.
435193323Sed  ///
436212904Sdim  /// As a special case, if Filename is "-", then the stream will use
437327952Sdim  /// STDOUT_FILENO instead of opening a file. This will not close the stdout
438327952Sdim  /// descriptor.
439341825Sdim  raw_fd_ostream(StringRef Filename, std::error_code &EC);
440280031Sdim  raw_fd_ostream(StringRef Filename, std::error_code &EC,
441341825Sdim                 sys::fs::CreationDisposition Disp);
442341825Sdim  raw_fd_ostream(StringRef Filename, std::error_code &EC,
443341825Sdim                 sys::fs::FileAccess Access);
444341825Sdim  raw_fd_ostream(StringRef Filename, std::error_code &EC,
445276479Sdim                 sys::fs::OpenFlags Flags);
446341825Sdim  raw_fd_ostream(StringRef Filename, std::error_code &EC,
447341825Sdim                 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
448341825Sdim                 sys::fs::OpenFlags Flags);
449193323Sed
450288943Sdim  /// FD is the file descriptor that this writes to.  If ShouldClose is true,
451327952Sdim  /// this closes the file when the stream is destroyed. If FD is for stdout or
452327952Sdim  /// stderr, it will not be closed.
453218893Sdim  raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
454198113Srdivacky
455288943Sdim  ~raw_fd_ostream() override;
456193323Sed
457288943Sdim  /// Manually flush the stream and close the file. Note that this does not call
458288943Sdim  /// fsync.
459193323Sed  void close();
460193323Sed
461288943Sdim  bool supportsSeeking() { return SupportsSeeking; }
462288943Sdim
463288943Sdim  /// Flushes the stream and repositions the underlying file descriptor position
464288943Sdim  /// to the offset specified from the beginning of the file.
465193323Sed  uint64_t seek(uint64_t off);
466193574Sed
467276479Sdim  raw_ostream &changeColor(enum Colors colors, bool bold=false,
468276479Sdim                           bool bg=false) override;
469276479Sdim  raw_ostream &resetColor() override;
470198090Srdivacky
471276479Sdim  raw_ostream &reverseColor() override;
472234982Sdim
473276479Sdim  bool is_displayed() const override;
474193323Sed
475276479Sdim  bool has_colors() const override;
476239462Sdim
477360784Sdim  void enable_colors(bool enable) override { ColorEnabled = enable; }
478360784Sdim
479327952Sdim  std::error_code error() const { return EC; }
480327952Sdim
481288943Sdim  /// Return the value of the flag in this raw_fd_ostream indicating whether an
482288943Sdim  /// output error has been encountered.
483212904Sdim  /// This doesn't implicitly flush any pending output.  Also, it doesn't
484239462Sdim  /// guarantee to detect all errors unless the stream has been closed.
485327952Sdim  bool has_error() const { return bool(EC); }
486193323Sed
487288943Sdim  /// Set the flag read by has_error() to false. If the error flag is set at the
488288943Sdim  /// time when this raw_ostream's destructor is called, report_fatal_error is
489288943Sdim  /// called to report the error. Use clear_error() after handling the error to
490288943Sdim  /// avoid this behavior.
491212904Sdim  ///
492212904Sdim  ///   "Errors should never pass silently.
493212904Sdim  ///    Unless explicitly silenced."
494212904Sdim  ///      - from The Zen of Python, by Tim Peters
495212904Sdim  ///
496327952Sdim  void clear_error() { EC = std::error_code(); }
497193323Sed};
498193323Sed
499288943Sdim/// This returns a reference to a raw_ostream for standard output. Use it like:
500288943Sdim/// outs() << "foo" << "bar";
501193323Sedraw_ostream &outs();
502193323Sed
503288943Sdim/// This returns a reference to a raw_ostream for standard error. Use it like:
504288943Sdim/// errs() << "foo" << "bar";
505193323Sedraw_ostream &errs();
506193323Sed
507288943Sdim/// This returns a reference to a raw_ostream which simply discards output.
508198090Srdivackyraw_ostream &nulls();
509193323Sed
510193323Sed//===----------------------------------------------------------------------===//
511193323Sed// Output Stream Adaptors
512193323Sed//===----------------------------------------------------------------------===//
513193323Sed
514288943Sdim/// A raw_ostream that writes to an std::string.  This is a simple adaptor
515288943Sdim/// class. This class does not encounter output errors.
516193323Sedclass raw_string_ostream : public raw_ostream {
517193323Sed  std::string &OS;
518193323Sed
519288943Sdim  /// See raw_ostream::write_impl.
520276479Sdim  void write_impl(const char *Ptr, size_t Size) override;
521193323Sed
522288943Sdim  /// Return the current position within the stream, not counting the bytes
523288943Sdim  /// currently in the buffer.
524276479Sdim  uint64_t current_pos() const override { return OS.size(); }
525296417Sdim
526193323Sedpublic:
527198090Srdivacky  explicit raw_string_ostream(std::string &O) : OS(O) {}
528288943Sdim  ~raw_string_ostream() override;
529193323Sed
530288943Sdim  /// Flushes the stream contents to the target string and returns  the string's
531288943Sdim  /// reference.
532193323Sed  std::string& str() {
533193323Sed    flush();
534193323Sed    return OS;
535193323Sed  }
536193323Sed};
537193323Sed
538288943Sdim/// A raw_ostream that writes to an SmallVector or SmallString.  This is a
539288943Sdim/// simple adaptor class. This class does not encounter output errors.
540296417Sdim/// raw_svector_ostream operates without a buffer, delegating all memory
541296417Sdim/// management to the SmallString. Thus the SmallString is always up-to-date,
542296417Sdim/// may be used directly and there is no need to call flush().
543288943Sdimclass raw_svector_ostream : public raw_pwrite_stream {
544193323Sed  SmallVectorImpl<char> &OS;
545193323Sed
546288943Sdim  /// See raw_ostream::write_impl.
547276479Sdim  void write_impl(const char *Ptr, size_t Size) override;
548193323Sed
549288943Sdim  void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
550288943Sdim
551296417Sdim  /// Return the current position within the stream.
552276479Sdim  uint64_t current_pos() const override;
553288943Sdim
554193323Sedpublic:
555198090Srdivacky  /// Construct a new raw_svector_ostream.
556198090Srdivacky  ///
557243830Sdim  /// \param O The vector to write to; this should generally have at least 128
558198090Srdivacky  /// bytes free to avoid any extraneous memory overhead.
559296417Sdim  explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
560296417Sdim    SetUnbuffered();
561296417Sdim  }
562193323Sed
563314564Sdim  ~raw_svector_ostream() override = default;
564314564Sdim
565296417Sdim  void flush() = delete;
566288943Sdim
567296417Sdim  /// Return a StringRef for the vector contents.
568296417Sdim  StringRef str() { return StringRef(OS.data(), OS.size()); }
569193323Sed};
570193323Sed
571288943Sdim/// A raw_ostream that discards all output.
572288943Sdimclass raw_null_ostream : public raw_pwrite_stream {
573288943Sdim  /// See raw_ostream::write_impl.
574276479Sdim  void write_impl(const char *Ptr, size_t size) override;
575288943Sdim  void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
576198113Srdivacky
577288943Sdim  /// Return the current position within the stream, not counting the bytes
578288943Sdim  /// currently in the buffer.
579276479Sdim  uint64_t current_pos() const override;
580198090Srdivacky
581198090Srdivackypublic:
582314564Sdim  explicit raw_null_ostream() = default;
583288943Sdim  ~raw_null_ostream() override;
584198090Srdivacky};
585198090Srdivacky
586288943Sdimclass buffer_ostream : public raw_svector_ostream {
587288943Sdim  raw_ostream &OS;
588288943Sdim  SmallVector<char, 0> Buffer;
589288943Sdim
590344779Sdim  virtual void anchor() override;
591344779Sdim
592288943Sdimpublic:
593296417Sdim  buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
594296417Sdim  ~buffer_ostream() override { OS << str(); }
595288943Sdim};
596288943Sdim
597314564Sdim} // end namespace llvm
598193323Sed
599296417Sdim#endif // LLVM_SUPPORT_RAW_OSTREAM_H
600