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