add a raw_ostream::indent method, to be used like:
[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   /// raw_fd_ostream - Open the specified file for writing. If an
338   /// error occurs, information about the error is put into ErrorInfo,
339   /// and the stream should be immediately destroyed; the string will
340   /// be empty if no error occurred.
341   ///
342   /// \param Filename - The file to open. If this is "-" then the
343   /// stream will use stdout instead.
344   /// \param Binary - The file should be opened in binary mode on
345   /// platforms that support this distinction.
346   /// \param Force - Don't consider the case where the file already
347   /// exists to be an error.
348   raw_fd_ostream(const char *Filename, bool Binary, bool Force,
349                  std::string &ErrorInfo);
350
351   /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
352   /// ShouldClose is true, this closes the file when the stream is destroyed.
353   raw_fd_ostream(int fd, bool shouldClose, 
354                  bool unbuffered=false) : raw_ostream(unbuffered), FD(fd), 
355                                           ShouldClose(shouldClose) {}
356   
357   ~raw_fd_ostream();
358
359   /// close - Manually flush the stream and close the file.
360   void close();
361
362   /// seek - Flushes the stream and repositions the underlying file descriptor
363   ///  positition to the offset specified from the beginning of the file.
364   uint64_t seek(uint64_t off);
365
366   virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
367                                    bool bg=false);
368   virtual raw_ostream &resetColor();
369 };
370
371 /// raw_stdout_ostream - This is a stream that always prints to stdout.
372 ///
373 class raw_stdout_ostream : public raw_fd_ostream {
374   // An out of line virtual method to provide a home for the class vtable.
375   virtual void handle();
376 public:
377   raw_stdout_ostream();
378 };
379
380 /// raw_stderr_ostream - This is a stream that always prints to stderr.
381 ///
382 class raw_stderr_ostream : public raw_fd_ostream {
383   // An out of line virtual method to provide a home for the class vtable.
384   virtual void handle();
385 public:
386   raw_stderr_ostream();
387 };
388
389 /// outs() - This returns a reference to a raw_ostream for standard output.
390 /// Use it like: outs() << "foo" << "bar";
391 raw_ostream &outs();
392
393 /// errs() - This returns a reference to a raw_ostream for standard error.
394 /// Use it like: errs() << "foo" << "bar";
395 raw_ostream &errs();
396
397 /// nulls() - This returns a reference to a raw_ostream which simply discards
398 /// output.
399 raw_ostream &nulls();
400
401 //===----------------------------------------------------------------------===//
402 // Output Stream Adaptors
403 //===----------------------------------------------------------------------===//
404
405 /// raw_os_ostream - A raw_ostream that writes to an std::ostream.  This is a
406 /// simple adaptor class.  It does not check for output errors; clients should
407 /// use the underlying stream to detect errors.
408 class raw_os_ostream : public raw_ostream {
409   std::ostream &OS;
410
411   /// write_impl - See raw_ostream::write_impl.
412   virtual void write_impl(const char *Ptr, size_t Size);
413
414   /// current_pos - Return the current position within the stream, not
415   /// counting the bytes currently in the buffer.
416   virtual uint64_t current_pos();
417
418 public:
419   raw_os_ostream(std::ostream &O) : OS(O) {}
420   ~raw_os_ostream();
421 };
422
423 /// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
424 /// simple adaptor class. This class does not encounter output errors.
425 class raw_string_ostream : public raw_ostream {
426   std::string &OS;
427
428   /// write_impl - See raw_ostream::write_impl.
429   virtual void write_impl(const char *Ptr, size_t Size);
430
431   /// current_pos - Return the current position within the stream, not
432   /// counting the bytes currently in the buffer.
433   virtual uint64_t current_pos() { return OS.size(); }
434 public:
435   explicit raw_string_ostream(std::string &O) : OS(O) {}
436   ~raw_string_ostream();
437
438   /// str - Flushes the stream contents to the target string and returns
439   ///  the string's reference.
440   std::string& str() {
441     flush();
442     return OS;
443   }
444 };
445
446 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
447 /// SmallString.  This is a simple adaptor class. This class does not
448 /// encounter output errors.
449 class raw_svector_ostream : public raw_ostream {
450   SmallVectorImpl<char> &OS;
451
452   /// write_impl - See raw_ostream::write_impl.
453   virtual void write_impl(const char *Ptr, size_t Size);
454
455   /// current_pos - Return the current position within the stream, not
456   /// counting the bytes currently in the buffer.
457   virtual uint64_t current_pos();
458 public:
459   /// Construct a new raw_svector_ostream.
460   ///
461   /// \arg O - The vector to write to; this should generally have at least 128
462   /// bytes free to avoid any extraneous memory overhead.
463   explicit raw_svector_ostream(SmallVectorImpl<char> &O);
464   ~raw_svector_ostream();
465
466   /// str - Flushes the stream contents to the target vector and return a
467   /// StringRef for the vector contents.
468   StringRef str();
469 };
470
471 /// raw_null_ostream - A raw_ostream that discards all output.
472 class raw_null_ostream : public raw_ostream {
473   /// write_impl - See raw_ostream::write_impl.
474   virtual void write_impl(const char *Ptr, size_t size);
475   
476   /// current_pos - Return the current position within the stream, not
477   /// counting the bytes currently in the buffer.
478   virtual uint64_t current_pos();
479
480 public:
481   explicit raw_null_ostream() {}
482   ~raw_null_ostream();
483 };
484
485 } // end llvm namespace
486
487 #endif