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