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