LLVM API Documentation

raw_ostream.h
Go to the documentation of this file.
00001 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the raw_ostream class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
00015 #define LLVM_SUPPORT_RAW_OSTREAM_H
00016 
00017 #include "llvm/ADT/StringRef.h"
00018 #include "llvm/Support/Compiler.h"
00019 #include "llvm/Support/DataTypes.h"
00020 #include <system_error>
00021 
00022 namespace llvm {
00023   class format_object_base;
00024   template <typename T>
00025   class SmallVectorImpl;
00026 
00027   namespace sys {
00028     namespace fs {
00029       enum OpenFlags : unsigned;
00030     }
00031   }
00032 
00033 /// raw_ostream - This class implements an extremely fast bulk output stream
00034 /// that can *only* output to a stream.  It does not support seeking, reopening,
00035 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
00036 /// a chunk at a time.
00037 class raw_ostream {
00038 private:
00039   void operator=(const raw_ostream &) LLVM_DELETED_FUNCTION;
00040   raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION;
00041 
00042   /// The buffer is handled in such a way that the buffer is
00043   /// uninitialized, unbuffered, or out of space when OutBufCur >=
00044   /// OutBufEnd. Thus a single comparison suffices to determine if we
00045   /// need to take the slow path to write a single character.
00046   ///
00047   /// The buffer is in one of three states:
00048   ///  1. Unbuffered (BufferMode == Unbuffered)
00049   ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
00050   ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
00051   ///               OutBufEnd - OutBufStart >= 1).
00052   ///
00053   /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
00054   /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
00055   /// managed by the subclass.
00056   ///
00057   /// If a subclass installs an external buffer using SetBuffer then it can wait
00058   /// for a \see write_impl() call to handle the data which has been put into
00059   /// this buffer.
00060   char *OutBufStart, *OutBufEnd, *OutBufCur;
00061 
00062   enum BufferKind {
00063     Unbuffered = 0,
00064     InternalBuffer,
00065     ExternalBuffer
00066   } BufferMode;
00067 
00068 public:
00069   // color order matches ANSI escape sequence, don't change
00070   enum Colors {
00071     BLACK=0,
00072     RED,
00073     GREEN,
00074     YELLOW,
00075     BLUE,
00076     MAGENTA,
00077     CYAN,
00078     WHITE,
00079     SAVEDCOLOR
00080   };
00081 
00082   explicit raw_ostream(bool unbuffered=false)
00083     : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
00084     // Start out ready to flush.
00085     OutBufStart = OutBufEnd = OutBufCur = nullptr;
00086   }
00087 
00088   virtual ~raw_ostream();
00089 
00090   /// tell - Return the current offset with the file.
00091   uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
00092 
00093   //===--------------------------------------------------------------------===//
00094   // Configuration Interface
00095   //===--------------------------------------------------------------------===//
00096 
00097   /// SetBuffered - Set the stream to be buffered, with an automatically
00098   /// determined buffer size.
00099   void SetBuffered();
00100 
00101   /// SetBufferSize - Set the stream to be buffered, using the
00102   /// specified buffer size.
00103   void SetBufferSize(size_t Size) {
00104     flush();
00105     SetBufferAndMode(new char[Size], Size, InternalBuffer);
00106   }
00107 
00108   size_t GetBufferSize() const {
00109     // If we're supposed to be buffered but haven't actually gotten around
00110     // to allocating the buffer yet, return the value that would be used.
00111     if (BufferMode != Unbuffered && OutBufStart == nullptr)
00112       return preferred_buffer_size();
00113 
00114     // Otherwise just return the size of the allocated buffer.
00115     return OutBufEnd - OutBufStart;
00116   }
00117 
00118   /// SetUnbuffered - Set the stream to be unbuffered. When
00119   /// unbuffered, the stream will flush after every write. This routine
00120   /// will also flush the buffer immediately when the stream is being
00121   /// set to unbuffered.
00122   void SetUnbuffered() {
00123     flush();
00124     SetBufferAndMode(nullptr, 0, Unbuffered);
00125   }
00126 
00127   size_t GetNumBytesInBuffer() const {
00128     return OutBufCur - OutBufStart;
00129   }
00130 
00131   //===--------------------------------------------------------------------===//
00132   // Data Output Interface
00133   //===--------------------------------------------------------------------===//
00134 
00135   void flush() {
00136     if (OutBufCur != OutBufStart)
00137       flush_nonempty();
00138   }
00139 
00140   raw_ostream &operator<<(char C) {
00141     if (OutBufCur >= OutBufEnd)
00142       return write(C);
00143     *OutBufCur++ = C;
00144     return *this;
00145   }
00146 
00147   raw_ostream &operator<<(unsigned char C) {
00148     if (OutBufCur >= OutBufEnd)
00149       return write(C);
00150     *OutBufCur++ = C;
00151     return *this;
00152   }
00153 
00154   raw_ostream &operator<<(signed char C) {
00155     if (OutBufCur >= OutBufEnd)
00156       return write(C);
00157     *OutBufCur++ = C;
00158     return *this;
00159   }
00160 
00161   raw_ostream &operator<<(StringRef Str) {
00162     // Inline fast path, particularly for strings with a known length.
00163     size_t Size = Str.size();
00164 
00165     // Make sure we can use the fast path.
00166     if (Size > (size_t)(OutBufEnd - OutBufCur))
00167       return write(Str.data(), Size);
00168 
00169     memcpy(OutBufCur, Str.data(), Size);
00170     OutBufCur += Size;
00171     return *this;
00172   }
00173 
00174   raw_ostream &operator<<(const char *Str) {
00175     // Inline fast path, particularly for constant strings where a sufficiently
00176     // smart compiler will simplify strlen.
00177 
00178     return this->operator<<(StringRef(Str));
00179   }
00180 
00181   raw_ostream &operator<<(const std::string &Str) {
00182     // Avoid the fast path, it would only increase code size for a marginal win.
00183     return write(Str.data(), Str.length());
00184   }
00185 
00186   raw_ostream &operator<<(unsigned long N);
00187   raw_ostream &operator<<(long N);
00188   raw_ostream &operator<<(unsigned long long N);
00189   raw_ostream &operator<<(long long N);
00190   raw_ostream &operator<<(const void *P);
00191   raw_ostream &operator<<(unsigned int N) {
00192     return this->operator<<(static_cast<unsigned long>(N));
00193   }
00194 
00195   raw_ostream &operator<<(int N) {
00196     return this->operator<<(static_cast<long>(N));
00197   }
00198 
00199   raw_ostream &operator<<(double N);
00200 
00201   /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
00202   raw_ostream &write_hex(unsigned long long N);
00203 
00204   /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
00205   /// anything that doesn't satisfy std::isprint into an escape sequence.
00206   raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
00207 
00208   raw_ostream &write(unsigned char C);
00209   raw_ostream &write(const char *Ptr, size_t Size);
00210 
00211   // Formatted output, see the format() function in Support/Format.h.
00212   raw_ostream &operator<<(const format_object_base &Fmt);
00213 
00214   /// indent - Insert 'NumSpaces' spaces.
00215   raw_ostream &indent(unsigned NumSpaces);
00216 
00217 
00218   /// Changes the foreground color of text that will be output from this point
00219   /// forward.
00220   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
00221   /// change only the bold attribute, and keep colors untouched
00222   /// @param Bold bold/brighter text, default false
00223   /// @param BG if true change the background, default: change foreground
00224   /// @returns itself so it can be used within << invocations
00225   virtual raw_ostream &changeColor(enum Colors Color,
00226                                    bool Bold = false,
00227                                    bool BG = false) {
00228     (void)Color;
00229     (void)Bold;
00230     (void)BG;
00231     return *this;
00232   }
00233 
00234   /// Resets the colors to terminal defaults. Call this when you are done
00235   /// outputting colored text, or before program exit.
00236   virtual raw_ostream &resetColor() { return *this; }
00237 
00238   /// Reverses the forground and background colors.
00239   virtual raw_ostream &reverseColor() { return *this; }
00240 
00241   /// This function determines if this stream is connected to a "tty" or
00242   /// "console" window. That is, the output would be displayed to the user
00243   /// rather than being put on a pipe or stored in a file.
00244   virtual bool is_displayed() const { return false; }
00245 
00246   /// This function determines if this stream is displayed and supports colors.
00247   virtual bool has_colors() const { return is_displayed(); }
00248 
00249   //===--------------------------------------------------------------------===//
00250   // Subclass Interface
00251   //===--------------------------------------------------------------------===//
00252 
00253 private:
00254   /// write_impl - The is the piece of the class that is implemented
00255   /// by subclasses.  This writes the \p Size bytes starting at
00256   /// \p Ptr to the underlying stream.
00257   ///
00258   /// This function is guaranteed to only be called at a point at which it is
00259   /// safe for the subclass to install a new buffer via SetBuffer.
00260   ///
00261   /// \param Ptr The start of the data to be written. For buffered streams this
00262   /// is guaranteed to be the start of the buffer.
00263   ///
00264   /// \param Size The number of bytes to be written.
00265   ///
00266   /// \invariant { Size > 0 }
00267   virtual void write_impl(const char *Ptr, size_t Size) = 0;
00268 
00269   // An out of line virtual method to provide a home for the class vtable.
00270   virtual void handle();
00271 
00272   /// current_pos - Return the current position within the stream, not
00273   /// counting the bytes currently in the buffer.
00274   virtual uint64_t current_pos() const = 0;
00275 
00276 protected:
00277   /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
00278   /// intended for use only by subclasses which can arrange for the output to go
00279   /// directly into the desired output buffer, instead of being copied on each
00280   /// flush.
00281   void SetBuffer(char *BufferStart, size_t Size) {
00282     SetBufferAndMode(BufferStart, Size, ExternalBuffer);
00283   }
00284 
00285   /// preferred_buffer_size - Return an efficient buffer size for the
00286   /// underlying output mechanism.
00287   virtual size_t preferred_buffer_size() const;
00288 
00289   /// getBufferStart - Return the beginning of the current stream buffer, or 0
00290   /// if the stream is unbuffered.
00291   const char *getBufferStart() const { return OutBufStart; }
00292 
00293   //===--------------------------------------------------------------------===//
00294   // Private Interface
00295   //===--------------------------------------------------------------------===//
00296 private:
00297   /// SetBufferAndMode - Install the given buffer and mode.
00298   void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
00299 
00300   /// flush_nonempty - Flush the current buffer, which is known to be
00301   /// non-empty. This outputs the currently buffered data and resets
00302   /// the buffer to empty.
00303   void flush_nonempty();
00304 
00305   /// copy_to_buffer - Copy data into the buffer. Size must not be
00306   /// greater than the number of unused bytes in the buffer.
00307   void copy_to_buffer(const char *Ptr, size_t Size);
00308 };
00309 
00310 //===----------------------------------------------------------------------===//
00311 // File Output Streams
00312 //===----------------------------------------------------------------------===//
00313 
00314 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
00315 ///
00316 class raw_fd_ostream : public raw_ostream {
00317   int FD;
00318   bool ShouldClose;
00319 
00320   /// Error This flag is true if an error of any kind has been detected.
00321   ///
00322   bool Error;
00323 
00324   /// Controls whether the stream should attempt to use atomic writes, when
00325   /// possible.
00326   bool UseAtomicWrites;
00327 
00328   uint64_t pos;
00329 
00330   /// write_impl - See raw_ostream::write_impl.
00331   void write_impl(const char *Ptr, size_t Size) override;
00332 
00333   /// current_pos - Return the current position within the stream, not
00334   /// counting the bytes currently in the buffer.
00335   uint64_t current_pos() const override { return pos; }
00336 
00337   /// preferred_buffer_size - Determine an efficient buffer size.
00338   size_t preferred_buffer_size() const override;
00339 
00340   /// error_detected - Set the flag indicating that an output error has
00341   /// been encountered.
00342   void error_detected() { Error = true; }
00343 
00344 public:
00345   /// Open the specified file for writing. If an error occurs, information
00346   /// about the error is put into EC, and the stream should be immediately
00347   /// destroyed;
00348   /// \p Flags allows optional flags to control how the file will be opened.
00349   ///
00350   /// As a special case, if Filename is "-", then the stream will use
00351   /// STDOUT_FILENO instead of opening a file. Note that it will still consider
00352   /// itself to own the file descriptor. In particular, it will close the
00353   /// file descriptor when it is done (this is necessary to detect
00354   /// output errors).
00355   raw_fd_ostream(StringRef Filename, std::error_code &EC,
00356                  sys::fs::OpenFlags Flags);
00357 
00358   /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
00359   /// ShouldClose is true, this closes the file when the stream is destroyed.
00360   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
00361 
00362   ~raw_fd_ostream();
00363 
00364   /// close - Manually flush the stream and close the file.
00365   /// Note that this does not call fsync.
00366   void close();
00367 
00368   /// seek - Flushes the stream and repositions the underlying file descriptor
00369   /// position to the offset specified from the beginning of the file.
00370   uint64_t seek(uint64_t off);
00371 
00372   /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
00373   /// individual output routines where possible.
00374   ///
00375   /// Note that because raw_ostream's are typically buffered, this flag is only
00376   /// sensible when used on unbuffered streams which will flush their output
00377   /// immediately.
00378   void SetUseAtomicWrites(bool Value) {
00379     UseAtomicWrites = Value;
00380   }
00381 
00382   raw_ostream &changeColor(enum Colors colors, bool bold=false,
00383                            bool bg=false) override;
00384   raw_ostream &resetColor() override;
00385 
00386   raw_ostream &reverseColor() override;
00387 
00388   bool is_displayed() const override;
00389 
00390   bool has_colors() const override;
00391 
00392   /// has_error - Return the value of the flag in this raw_fd_ostream indicating
00393   /// whether an output error has been encountered.
00394   /// This doesn't implicitly flush any pending output.  Also, it doesn't
00395   /// guarantee to detect all errors unless the stream has been closed.
00396   bool has_error() const {
00397     return Error;
00398   }
00399 
00400   /// clear_error - Set the flag read by has_error() to false. If the error
00401   /// flag is set at the time when this raw_ostream's destructor is called,
00402   /// report_fatal_error is called to report the error. Use clear_error()
00403   /// after handling the error to avoid this behavior.
00404   ///
00405   ///   "Errors should never pass silently.
00406   ///    Unless explicitly silenced."
00407   ///      - from The Zen of Python, by Tim Peters
00408   ///
00409   void clear_error() {
00410     Error = false;
00411   }
00412 };
00413 
00414 /// outs() - This returns a reference to a raw_ostream for standard output.
00415 /// Use it like: outs() << "foo" << "bar";
00416 raw_ostream &outs();
00417 
00418 /// errs() - This returns a reference to a raw_ostream for standard error.
00419 /// Use it like: errs() << "foo" << "bar";
00420 raw_ostream &errs();
00421 
00422 /// nulls() - This returns a reference to a raw_ostream which simply discards
00423 /// output.
00424 raw_ostream &nulls();
00425 
00426 //===----------------------------------------------------------------------===//
00427 // Output Stream Adaptors
00428 //===----------------------------------------------------------------------===//
00429 
00430 /// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
00431 /// simple adaptor class. This class does not encounter output errors.
00432 class raw_string_ostream : public raw_ostream {
00433   std::string &OS;
00434 
00435   /// write_impl - See raw_ostream::write_impl.
00436   void write_impl(const char *Ptr, size_t Size) override;
00437 
00438   /// current_pos - Return the current position within the stream, not
00439   /// counting the bytes currently in the buffer.
00440   uint64_t current_pos() const override { return OS.size(); }
00441 public:
00442   explicit raw_string_ostream(std::string &O) : OS(O) {}
00443   ~raw_string_ostream();
00444 
00445   /// str - Flushes the stream contents to the target string and returns
00446   ///  the string's reference.
00447   std::string& str() {
00448     flush();
00449     return OS;
00450   }
00451 };
00452 
00453 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
00454 /// SmallString.  This is a simple adaptor class. This class does not
00455 /// encounter output errors.
00456 class raw_svector_ostream : public raw_ostream {
00457   SmallVectorImpl<char> &OS;
00458 
00459   /// write_impl - See raw_ostream::write_impl.
00460   void write_impl(const char *Ptr, size_t Size) override;
00461 
00462   /// current_pos - Return the current position within the stream, not
00463   /// counting the bytes currently in the buffer.
00464   uint64_t current_pos() const override;
00465 public:
00466   /// Construct a new raw_svector_ostream.
00467   ///
00468   /// \param O The vector to write to; this should generally have at least 128
00469   /// bytes free to avoid any extraneous memory overhead.
00470   explicit raw_svector_ostream(SmallVectorImpl<char> &O);
00471   ~raw_svector_ostream();
00472 
00473   /// resync - This is called when the SmallVector we're appending to is changed
00474   /// outside of the raw_svector_ostream's control.  It is only safe to do this
00475   /// if the raw_svector_ostream has previously been flushed.
00476   void resync();
00477 
00478   /// str - Flushes the stream contents to the target vector and return a
00479   /// StringRef for the vector contents.
00480   StringRef str();
00481 };
00482 
00483 /// raw_null_ostream - A raw_ostream that discards all output.
00484 class raw_null_ostream : public raw_ostream {
00485   /// write_impl - See raw_ostream::write_impl.
00486   void write_impl(const char *Ptr, size_t size) override;
00487 
00488   /// current_pos - Return the current position within the stream, not
00489   /// counting the bytes currently in the buffer.
00490   uint64_t current_pos() const override;
00491 
00492 public:
00493   explicit raw_null_ostream() {}
00494   ~raw_null_ostream();
00495 };
00496 
00497 } // end llvm namespace
00498 
00499 #endif