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