Home | History | Annotate | Download | only in Support
      1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file defines the raw_ostream class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
     15 #define LLVM_SUPPORT_RAW_OSTREAM_H
     16 
     17 #include "llvm/ADT/StringRef.h"
     18 #include "llvm/Support/Compiler.h"
     19 #include "llvm/Support/DataTypes.h"
     20 #include "llvm/Support/FileSystem.h"
     21 
     22 namespace llvm {
     23   class format_object_base;
     24   template <typename T>
     25   class SmallVectorImpl;
     26 
     27 /// raw_ostream - This class implements an extremely fast bulk output stream
     28 /// that can *only* output to a stream.  It does not support seeking, reopening,
     29 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
     30 /// a chunk at a time.
     31 class raw_ostream {
     32 private:
     33   void operator=(const raw_ostream &) LLVM_DELETED_FUNCTION;
     34   raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION;
     35 
     36   /// The buffer is handled in such a way that the buffer is
     37   /// uninitialized, unbuffered, or out of space when OutBufCur >=
     38   /// OutBufEnd. Thus a single comparison suffices to determine if we
     39   /// need to take the slow path to write a single character.
     40   ///
     41   /// The buffer is in one of three states:
     42   ///  1. Unbuffered (BufferMode == Unbuffered)
     43   ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
     44   ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
     45   ///               OutBufEnd - OutBufStart >= 1).
     46   ///
     47   /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
     48   /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
     49   /// managed by the subclass.
     50   ///
     51   /// If a subclass installs an external buffer using SetBuffer then it can wait
     52   /// for a \see write_impl() call to handle the data which has been put into
     53   /// this buffer.
     54   char *OutBufStart, *OutBufEnd, *OutBufCur;
     55 
     56   enum BufferKind {
     57     Unbuffered = 0,
     58     InternalBuffer,
     59     ExternalBuffer
     60   } BufferMode;
     61 
     62 public:
     63   // color order matches ANSI escape sequence, don't change
     64   enum Colors {
     65     BLACK=0,
     66     RED,
     67     GREEN,
     68     YELLOW,
     69     BLUE,
     70     MAGENTA,
     71     CYAN,
     72     WHITE,
     73     SAVEDCOLOR
     74   };
     75 
     76   explicit raw_ostream(bool unbuffered=false)
     77     : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
     78     // Start out ready to flush.
     79     OutBufStart = OutBufEnd = OutBufCur = 0;
     80   }
     81 
     82   virtual ~raw_ostream();
     83 
     84   /// tell - Return the current offset with the file.
     85   uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
     86 
     87   //===--------------------------------------------------------------------===//
     88   // Configuration Interface
     89   //===--------------------------------------------------------------------===//
     90 
     91   /// SetBuffered - Set the stream to be buffered, with an automatically
     92   /// determined buffer size.
     93   void SetBuffered();
     94 
     95   /// SetBufferSize - Set the stream to be buffered, using the
     96   /// specified buffer size.
     97   void SetBufferSize(size_t Size) {
     98     flush();
     99     SetBufferAndMode(new char[Size], Size, InternalBuffer);
    100   }
    101 
    102   size_t GetBufferSize() const {
    103     // If we're supposed to be buffered but haven't actually gotten around
    104     // to allocating the buffer yet, return the value that would be used.
    105     if (BufferMode != Unbuffered && OutBufStart == 0)
    106       return preferred_buffer_size();
    107 
    108     // Otherwise just return the size of the allocated buffer.
    109     return OutBufEnd - OutBufStart;
    110   }
    111 
    112   /// SetUnbuffered - Set the stream to be unbuffered. When
    113   /// unbuffered, the stream will flush after every write. This routine
    114   /// will also flush the buffer immediately when the stream is being
    115   /// set to unbuffered.
    116   void SetUnbuffered() {
    117     flush();
    118     SetBufferAndMode(0, 0, Unbuffered);
    119   }
    120 
    121   size_t GetNumBytesInBuffer() const {
    122     return OutBufCur - OutBufStart;
    123   }
    124 
    125   //===--------------------------------------------------------------------===//
    126   // Data Output Interface
    127   //===--------------------------------------------------------------------===//
    128 
    129   void flush() {
    130     if (OutBufCur != OutBufStart)
    131       flush_nonempty();
    132   }
    133 
    134   raw_ostream &operator<<(char C) {
    135     if (OutBufCur >= OutBufEnd)
    136       return write(C);
    137     *OutBufCur++ = C;
    138     return *this;
    139   }
    140 
    141   raw_ostream &operator<<(unsigned char C) {
    142     if (OutBufCur >= OutBufEnd)
    143       return write(C);
    144     *OutBufCur++ = C;
    145     return *this;
    146   }
    147 
    148   raw_ostream &operator<<(signed char C) {
    149     if (OutBufCur >= OutBufEnd)
    150       return write(C);
    151     *OutBufCur++ = C;
    152     return *this;
    153   }
    154 
    155   raw_ostream &operator<<(StringRef Str) {
    156     // Inline fast path, particularly for strings with a known length.
    157     size_t Size = Str.size();
    158 
    159     // Make sure we can use the fast path.
    160     if (OutBufCur+Size > OutBufEnd)
    161       return write(Str.data(), Size);
    162 
    163     memcpy(OutBufCur, Str.data(), Size);
    164     OutBufCur += Size;
    165     return *this;
    166   }
    167 
    168   raw_ostream &operator<<(const char *Str) {
    169     // Inline fast path, particularly for constant strings where a sufficiently
    170     // smart compiler will simplify strlen.
    171 
    172     return this->operator<<(StringRef(Str));
    173   }
    174 
    175   raw_ostream &operator<<(const std::string &Str) {
    176     // Avoid the fast path, it would only increase code size for a marginal win.
    177     return write(Str.data(), Str.length());
    178   }
    179 
    180   raw_ostream &operator<<(unsigned long N);
    181   raw_ostream &operator<<(long N);
    182   raw_ostream &operator<<(unsigned long long N);
    183   raw_ostream &operator<<(long long N);
    184   raw_ostream &operator<<(const void *P);
    185   raw_ostream &operator<<(unsigned int N) {
    186     return this->operator<<(static_cast<unsigned long>(N));
    187   }
    188 
    189   raw_ostream &operator<<(int N) {
    190     return this->operator<<(static_cast<long>(N));
    191   }
    192 
    193   raw_ostream &operator<<(double N);
    194 
    195   /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
    196   raw_ostream &write_hex(unsigned long long N);
    197 
    198   /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
    199   /// anything that doesn't satisfy std::isprint into an escape sequence.
    200   raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
    201 
    202   raw_ostream &write(unsigned char C);
    203   raw_ostream &write(const char *Ptr, size_t Size);
    204 
    205   // Formatted output, see the format() function in Support/Format.h.
    206   raw_ostream &operator<<(const format_object_base &Fmt);
    207 
    208   /// indent - Insert 'NumSpaces' spaces.
    209   raw_ostream &indent(unsigned NumSpaces);
    210 
    211 
    212   /// Changes the foreground color of text that will be output from this point
    213   /// forward.
    214   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
    215   /// change only the bold attribute, and keep colors untouched
    216   /// @param Bold bold/brighter text, default false
    217   /// @param BG if true change the background, default: change foreground
    218   /// @returns itself so it can be used within << invocations
    219   virtual raw_ostream &changeColor(enum Colors Color,
    220                                    bool Bold = false,
    221                                    bool BG = false) {
    222     (void)Color;
    223     (void)Bold;
    224     (void)BG;
    225     return *this;
    226   }
    227 
    228   /// Resets the colors to terminal defaults. Call this when you are done
    229   /// outputting colored text, or before program exit.
    230   virtual raw_ostream &resetColor() { return *this; }
    231 
    232   /// Reverses the forground and background colors.
    233   virtual raw_ostream &reverseColor() { return *this; }
    234 
    235   /// This function determines if this stream is connected to a "tty" or
    236   /// "console" window. That is, the output would be displayed to the user
    237   /// rather than being put on a pipe or stored in a file.
    238   virtual bool is_displayed() const { return false; }
    239 
    240   /// This function determines if this stream is displayed and supports colors.
    241   virtual bool has_colors() const { return is_displayed(); }
    242 
    243   //===--------------------------------------------------------------------===//
    244   // Subclass Interface
    245   //===--------------------------------------------------------------------===//
    246 
    247 private:
    248   /// write_impl - The is the piece of the class that is implemented
    249   /// by subclasses.  This writes the \p Size bytes starting at
    250   /// \p Ptr to the underlying stream.
    251   ///
    252   /// This function is guaranteed to only be called at a point at which it is
    253   /// safe for the subclass to install a new buffer via SetBuffer.
    254   ///
    255   /// \param Ptr The start of the data to be written. For buffered streams this
    256   /// is guaranteed to be the start of the buffer.
    257   ///
    258   /// \param Size The number of bytes to be written.
    259   ///
    260   /// \invariant { Size > 0 }
    261   virtual void write_impl(const char *Ptr, size_t Size) = 0;
    262 
    263   // An out of line virtual method to provide a home for the class vtable.
    264   virtual void handle();
    265 
    266   /// current_pos - Return the current position within the stream, not
    267   /// counting the bytes currently in the buffer.
    268   virtual uint64_t current_pos() const = 0;
    269 
    270 protected:
    271   /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
    272   /// intended for use only by subclasses which can arrange for the output to go
    273   /// directly into the desired output buffer, instead of being copied on each
    274   /// flush.
    275   void SetBuffer(char *BufferStart, size_t Size) {
    276     SetBufferAndMode(BufferStart, Size, ExternalBuffer);
    277   }
    278 
    279   /// preferred_buffer_size - Return an efficient buffer size for the
    280   /// underlying output mechanism.
    281   virtual size_t preferred_buffer_size() const;
    282 
    283   /// getBufferStart - Return the beginning of the current stream buffer, or 0
    284   /// if the stream is unbuffered.
    285   const char *getBufferStart() const { return OutBufStart; }
    286 
    287   //===--------------------------------------------------------------------===//
    288   // Private Interface
    289   //===--------------------------------------------------------------------===//
    290 private:
    291   /// SetBufferAndMode - Install the given buffer and mode.
    292   void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
    293 
    294   /// flush_nonempty - Flush the current buffer, which is known to be
    295   /// non-empty. This outputs the currently buffered data and resets
    296   /// the buffer to empty.
    297   void flush_nonempty();
    298 
    299   /// copy_to_buffer - Copy data into the buffer. Size must not be
    300   /// greater than the number of unused bytes in the buffer.
    301   void copy_to_buffer(const char *Ptr, size_t Size);
    302 };
    303 
    304 //===----------------------------------------------------------------------===//
    305 // File Output Streams
    306 //===----------------------------------------------------------------------===//
    307 
    308 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
    309 ///
    310 class raw_fd_ostream : public raw_ostream {
    311   int FD;
    312   bool ShouldClose;
    313 
    314   /// Error This flag is true if an error of any kind has been detected.
    315   ///
    316   bool Error;
    317 
    318   /// Controls whether the stream should attempt to use atomic writes, when
    319   /// possible.
    320   bool UseAtomicWrites;
    321 
    322   uint64_t pos;
    323 
    324   /// write_impl - See raw_ostream::write_impl.
    325   virtual void write_impl(const char *Ptr, size_t Size) LLVM_OVERRIDE;
    326 
    327   /// current_pos - Return the current position within the stream, not
    328   /// counting the bytes currently in the buffer.
    329   virtual uint64_t current_pos() const LLVM_OVERRIDE { return pos; }
    330 
    331   /// preferred_buffer_size - Determine an efficient buffer size.
    332   virtual size_t preferred_buffer_size() const LLVM_OVERRIDE;
    333 
    334   /// error_detected - Set the flag indicating that an output error has
    335   /// been encountered.
    336   void error_detected() { Error = true; }
    337 
    338 public:
    339   /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
    340   /// information about the error is put into ErrorInfo, and the stream should
    341   /// be immediately destroyed; the string will be empty if no error occurred.
    342   /// This allows optional flags to control how the file will be opened.
    343   ///
    344   /// As a special case, if Filename is "-", then the stream will use
    345   /// STDOUT_FILENO instead of opening a file. Note that it will still consider
    346   /// itself to own the file descriptor. In particular, it will close the
    347   /// file descriptor when it is done (this is necessary to detect
    348   /// output errors).
    349   raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
    350                  sys::fs::OpenFlags Flags = sys::fs::F_None);
    351 
    352   /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
    353   /// ShouldClose is true, this closes the file when the stream is destroyed.
    354   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
    355 
    356   ~raw_fd_ostream();
    357 
    358   /// close - Manually flush the stream and close the file.
    359   /// Note that this does not call fsync.
    360   void close();
    361 
    362   /// seek - Flushes the stream and repositions the underlying file descriptor
    363   /// position to the offset specified from the beginning of the file.
    364   uint64_t seek(uint64_t off);
    365 
    366   /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
    367   /// individual output routines where possible.
    368   ///
    369   /// Note that because raw_ostream's are typically buffered, this flag is only
    370   /// sensible when used on unbuffered streams which will flush their output
    371   /// immediately.
    372   void SetUseAtomicWrites(bool Value) {
    373     UseAtomicWrites = Value;
    374   }
    375 
    376   virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
    377                                    bool bg=false) LLVM_OVERRIDE;
    378   virtual raw_ostream &resetColor() LLVM_OVERRIDE;
    379 
    380   virtual raw_ostream &reverseColor() LLVM_OVERRIDE;
    381 
    382   virtual bool is_displayed() const LLVM_OVERRIDE;
    383 
    384   virtual bool has_colors() const LLVM_OVERRIDE;
    385 
    386   /// has_error - Return the value of the flag in this raw_fd_ostream indicating
    387   /// whether an output error has been encountered.
    388   /// This doesn't implicitly flush any pending output.  Also, it doesn't
    389   /// guarantee to detect all errors unless the stream has been closed.
    390   bool has_error() const {
    391     return Error;
    392   }
    393 
    394   /// clear_error - Set the flag read by has_error() to false. If the error
    395   /// flag is set at the time when this raw_ostream's destructor is called,
    396   /// report_fatal_error is called to report the error. Use clear_error()
    397   /// after handling the error to avoid this behavior.
    398   ///
    399   ///   "Errors should never pass silently.
    400   ///    Unless explicitly silenced."
    401   ///      - from The Zen of Python, by Tim Peters
    402   ///
    403   void clear_error() {
    404     Error = false;
    405   }
    406 };
    407 
    408 /// outs() - This returns a reference to a raw_ostream for standard output.
    409 /// Use it like: outs() << "foo" << "bar";
    410 raw_ostream &outs();
    411 
    412 /// errs() - This returns a reference to a raw_ostream for standard error.
    413 /// Use it like: errs() << "foo" << "bar";
    414 raw_ostream &errs();
    415 
    416 /// nulls() - This returns a reference to a raw_ostream which simply discards
    417 /// output.
    418 raw_ostream &nulls();
    419 
    420 //===----------------------------------------------------------------------===//
    421 // Output Stream Adaptors
    422 //===----------------------------------------------------------------------===//
    423 
    424 /// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
    425 /// simple adaptor class. This class does not encounter output errors.
    426 class raw_string_ostream : public raw_ostream {
    427   std::string &OS;
    428 
    429   /// write_impl - See raw_ostream::write_impl.
    430   virtual void write_impl(const char *Ptr, size_t Size) LLVM_OVERRIDE;
    431 
    432   /// current_pos - Return the current position within the stream, not
    433   /// counting the bytes currently in the buffer.
    434   virtual uint64_t current_pos() const LLVM_OVERRIDE { return OS.size(); }
    435 public:
    436   explicit raw_string_ostream(std::string &O) : OS(O) {}
    437   ~raw_string_ostream();
    438 
    439   /// str - Flushes the stream contents to the target string and returns
    440   ///  the string's reference.
    441   std::string& str() {
    442     flush();
    443     return OS;
    444   }
    445 };
    446 
    447 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
    448 /// SmallString.  This is a simple adaptor class. This class does not
    449 /// encounter output errors.
    450 class raw_svector_ostream : public raw_ostream {
    451   SmallVectorImpl<char> &OS;
    452 
    453   /// write_impl - See raw_ostream::write_impl.
    454   virtual void write_impl(const char *Ptr, size_t Size) LLVM_OVERRIDE;
    455 
    456   /// current_pos - Return the current position within the stream, not
    457   /// counting the bytes currently in the buffer.
    458   virtual uint64_t current_pos() const LLVM_OVERRIDE;
    459 public:
    460   /// Construct a new raw_svector_ostream.
    461   ///
    462   /// \param O The vector to write to; this should generally have at least 128
    463   /// bytes free to avoid any extraneous memory overhead.
    464   explicit raw_svector_ostream(SmallVectorImpl<char> &O);
    465   ~raw_svector_ostream();
    466 
    467   /// resync - This is called when the SmallVector we're appending to is changed
    468   /// outside of the raw_svector_ostream's control.  It is only safe to do this
    469   /// if the raw_svector_ostream has previously been flushed.
    470   void resync();
    471 
    472   /// str - Flushes the stream contents to the target vector and return a
    473   /// StringRef for the vector contents.
    474   StringRef str();
    475 };
    476 
    477 /// raw_null_ostream - A raw_ostream that discards all output.
    478 class raw_null_ostream : public raw_ostream {
    479   /// write_impl - See raw_ostream::write_impl.
    480   virtual void write_impl(const char *Ptr, size_t size) LLVM_OVERRIDE;
    481 
    482   /// current_pos - Return the current position within the stream, not
    483   /// counting the bytes currently in the buffer.
    484   virtual uint64_t current_pos() const LLVM_OVERRIDE;
    485 
    486 public:
    487   explicit raw_null_ostream() {}
    488   ~raw_null_ostream();
    489 };
    490 
    491 } // end llvm namespace
    492 
    493 #endif
    494