Add support for outputting ANSI colors to raw_fd_ostream.
[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 <cassert>
19 #include <cstring>
20 #include <string>
21 #include <iosfwd>
22
23 namespace llvm {
24   class format_object_base;
25   template <typename T>
26   class SmallVectorImpl;
27
28 /// raw_ostream - This class implements an extremely fast bulk output stream
29 /// that can *only* output to a stream.  It does not support seeking, reopening,
30 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
31 /// a chunk at a time.
32 class raw_ostream {
33 private:
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 (Unbuffered == true)
41   ///  1. Uninitialized (Unbuffered == false && OutBufStart == 0).
42   ///  2. Buffered (Unbuffered == false && OutBufStart != 0 &&
43   ///               OutBufEnd - OutBufStart >= 64).
44   char *OutBufStart, *OutBufEnd, *OutBufCur;
45   bool Unbuffered;
46
47 public:
48   // color order matches ANSI escape sequence, don't change
49   enum Colors {
50     BLACK=0,
51     RED,
52     GREEN,
53     YELLOW,
54     BLUE,
55     MAGENTA,
56     CYAN,
57     WHITE,
58     SAVEDCOLOR
59   };
60
61   explicit raw_ostream(bool unbuffered=false) : Unbuffered(unbuffered) {
62     // Start out ready to flush.
63     OutBufStart = OutBufEnd = OutBufCur = 0;
64   }
65
66   virtual ~raw_ostream() {
67     delete [] OutBufStart;
68   }
69
70   /// tell - Return the current offset with the file.
71   uint64_t tell() { return current_pos() + GetNumBytesInBuffer(); }
72
73   //===--------------------------------------------------------------------===//
74   // Configuration Interface
75   //===--------------------------------------------------------------------===//
76
77   /// SetBufferSize - Set the internal buffer size to the specified amount
78   /// instead of the default.
79   void SetBufferSize(unsigned Size=4096) {
80     assert(Size >= 64 &&
81            "Buffer size must be somewhat large for invariants to hold");
82     flush();
83
84     delete [] OutBufStart;
85     OutBufStart = new char[Size];
86     OutBufEnd = OutBufStart+Size;
87     OutBufCur = OutBufStart;
88     Unbuffered = false;
89   }
90
91   /// SetUnbuffered - Set the streams buffering status. When
92   /// unbuffered the stream will flush after every write. This routine
93   /// will also flush the buffer immediately when the stream is being
94   /// set to unbuffered.
95   void SetUnbuffered() {
96     flush();
97     
98     delete [] OutBufStart;
99     OutBufStart = OutBufEnd = OutBufCur = 0;
100     Unbuffered = true;
101   }
102
103   unsigned GetNumBytesInBuffer() const {
104     return OutBufCur - OutBufStart;
105   }
106
107   //===--------------------------------------------------------------------===//
108   // Data Output Interface
109   //===--------------------------------------------------------------------===//
110
111   void flush() {
112     if (OutBufCur != OutBufStart)
113       flush_nonempty();
114   }
115
116   raw_ostream &operator<<(char C) {
117     if (OutBufCur >= OutBufEnd)
118       return write(C);
119     *OutBufCur++ = C;
120     return *this;
121   }
122
123   raw_ostream &operator<<(unsigned char C) {
124     if (OutBufCur >= OutBufEnd)
125       return write(C);
126     *OutBufCur++ = C;
127     return *this;
128   }
129
130   raw_ostream &operator<<(signed char C) {
131     if (OutBufCur >= OutBufEnd)
132       return write(C);
133     *OutBufCur++ = C;
134     return *this;
135   }
136
137   raw_ostream &operator<<(const char *Str) {
138     // Inline fast path, particulary for constant strings where a
139     // sufficiently smart compiler will simplify strlen.
140
141     unsigned Size = strlen(Str);
142
143     // Make sure we can use the fast path.
144     if (OutBufCur+Size > OutBufEnd)
145       return write(Str, Size);
146
147     memcpy(OutBufCur, Str, Size);
148     OutBufCur += Size;
149     return *this;
150   }
151
152   raw_ostream &operator<<(const std::string& Str) {
153     write(Str.data(), Str.length());
154     return *this;
155   }
156
157   raw_ostream &operator<<(unsigned long N);
158   raw_ostream &operator<<(long N);
159   raw_ostream &operator<<(unsigned long long N);
160   raw_ostream &operator<<(long long N);
161   raw_ostream &operator<<(const void *P);
162   raw_ostream &operator<<(unsigned int N) {
163     this->operator<<(static_cast<unsigned long>(N));
164     return *this;
165   }
166
167   raw_ostream &operator<<(int N) {
168     this->operator<<(static_cast<long>(N));
169     return *this;
170   }
171
172   raw_ostream &operator<<(double N) {
173     this->operator<<(ftostr(N));
174     return *this;
175   }
176
177   raw_ostream &write(unsigned char C);
178   raw_ostream &write(const char *Ptr, unsigned Size);
179
180   // Formatted output, see the format() function in Support/Format.h.
181   raw_ostream &operator<<(const format_object_base &Fmt);
182
183   /// Changes the foreground color of text that will be output from this point
184   /// forward.
185   /// @param colors ANSI color to use, the special SAVEDCOLOR can be used to
186   /// change only the bold attribute, and keep colors untouched
187   /// @param bold bold/brighter text, default false
188   /// @param bg if true change the background, default: change foreground
189   /// @returns itself so it can be used within << invocations
190   virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
191                                    bool  bg=false) { return *this; }
192
193   /// Resets the colors to terminal defaults. Call this when you are done
194   /// outputting colored text, or before program exit.
195   virtual raw_ostream &resetColor() { return *this; }
196
197   //===--------------------------------------------------------------------===//
198   // Subclass Interface
199   //===--------------------------------------------------------------------===//
200
201 private:
202   /// write_impl - The is the piece of the class that is implemented
203   /// by subclasses.  This writes the \args Size bytes starting at
204   /// \arg Ptr to the underlying stream.
205   /// 
206   /// \invariant { Size > 0 }
207   virtual void write_impl(const char *Ptr, unsigned Size) = 0;
208
209   // An out of line virtual method to provide a home for the class vtable.
210   virtual void handle();
211
212   /// current_pos - Return the current position within the stream, not
213   /// counting the bytes currently in the buffer.
214   virtual uint64_t current_pos() = 0;
215
216   //===--------------------------------------------------------------------===//
217   // Private Interface
218   //===--------------------------------------------------------------------===//
219 private:
220   /// flush_nonempty - Flush the current buffer, which is known to be
221   /// non-empty. This outputs the currently buffered data and resets
222   /// the buffer to empty.
223   void flush_nonempty();
224 };
225
226 //===----------------------------------------------------------------------===//
227 // File Output Streams
228 //===----------------------------------------------------------------------===//
229
230 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
231 ///
232 class raw_fd_ostream : public raw_ostream {
233   int FD;
234   bool ShouldClose;
235   uint64_t pos;
236
237   /// write_impl - See raw_ostream::write_impl.
238   virtual void write_impl(const char *Ptr, unsigned Size);
239
240   /// current_pos - Return the current position within the stream, not
241   /// counting the bytes currently in the buffer.
242   virtual uint64_t current_pos() { return pos; }
243
244 public:
245   /// raw_fd_ostream - Open the specified file for writing. If an
246   /// error occurs, information about the error is put into ErrorInfo,
247   /// and the stream should be immediately destroyed; the string will
248   /// be empty if no error occurred.
249   ///
250   /// \param Filename - The file to open. If this is "-" then the
251   /// stream will use stdout instead.
252   /// \param Binary - The file should be opened in binary mode on
253   /// platforms that support this distinction.
254   raw_fd_ostream(const char *Filename, bool Binary, std::string &ErrorInfo);
255
256   /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
257   /// ShouldClose is true, this closes the file when the stream is destroyed.
258   raw_fd_ostream(int fd, bool shouldClose, 
259                  bool unbuffered=false) : raw_ostream(unbuffered), FD(fd), 
260                                           ShouldClose(shouldClose) {}
261   
262   ~raw_fd_ostream();
263
264   /// close - Manually flush the stream and close the file.
265   void close();
266
267   /// tell - Return the current offset with the file.
268   uint64_t tell() { return pos + GetNumBytesInBuffer(); }
269
270   /// seek - Flushes the stream and repositions the underlying file descriptor
271   ///  positition to the offset specified from the beginning of the file.
272   uint64_t seek(uint64_t off);
273
274   virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
275                                    bool bg=false);
276   virtual raw_ostream &resetColor();
277 };
278
279 /// raw_stdout_ostream - This is a stream that always prints to stdout.
280 ///
281 class raw_stdout_ostream : public raw_fd_ostream {
282   // An out of line virtual method to provide a home for the class vtable.
283   virtual void handle();
284 public:
285   raw_stdout_ostream();
286 };
287
288 /// raw_stderr_ostream - This is a stream that always prints to stderr.
289 ///
290 class raw_stderr_ostream : public raw_fd_ostream {
291   // An out of line virtual method to provide a home for the class vtable.
292   virtual void handle();
293 public:
294   raw_stderr_ostream();
295 };
296
297 /// outs() - This returns a reference to a raw_ostream for standard output.
298 /// Use it like: outs() << "foo" << "bar";
299 raw_ostream &outs();
300
301 /// errs() - This returns a reference to a raw_ostream for standard error.
302 /// Use it like: errs() << "foo" << "bar";
303 raw_ostream &errs();
304
305
306 //===----------------------------------------------------------------------===//
307 // Output Stream Adaptors
308 //===----------------------------------------------------------------------===//
309
310 /// raw_os_ostream - A raw_ostream that writes to an std::ostream.  This is a
311 /// simple adaptor class.
312 class raw_os_ostream : public raw_ostream {
313   std::ostream &OS;
314
315   /// write_impl - See raw_ostream::write_impl.
316   virtual void write_impl(const char *Ptr, unsigned Size);
317
318   /// current_pos - Return the current position within the stream, not
319   /// counting the bytes currently in the buffer.
320   virtual uint64_t current_pos();
321
322 public:
323   raw_os_ostream(std::ostream &O) : OS(O) {}
324   ~raw_os_ostream();
325
326   /// tell - Return the current offset with the stream.
327   uint64_t tell();
328 };
329
330 /// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
331 /// simple adaptor class.
332 class raw_string_ostream : public raw_ostream {
333   std::string &OS;
334
335   /// write_impl - See raw_ostream::write_impl.
336   virtual void write_impl(const char *Ptr, unsigned Size);
337
338   /// current_pos - Return the current position within the stream, not
339   /// counting the bytes currently in the buffer.
340   virtual uint64_t current_pos() { return OS.size(); }
341 public:
342   raw_string_ostream(std::string &O) : OS(O) {}
343   ~raw_string_ostream();
344
345   /// tell - Return the current offset with the stream.
346   uint64_t tell() { return OS.size() + GetNumBytesInBuffer(); }
347
348   /// str - Flushes the stream contents to the target string and returns
349   ///  the string's reference.
350   std::string& str() {
351     flush();
352     return OS;
353   }
354 };
355
356 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
357 /// SmallString.  This is a simple adaptor class.
358 class raw_svector_ostream : public raw_ostream {
359   SmallVectorImpl<char> &OS;
360
361   /// write_impl - See raw_ostream::write_impl.
362   virtual void write_impl(const char *Ptr, unsigned Size);
363
364   /// current_pos - Return the current position within the stream, not
365   /// counting the bytes currently in the buffer.
366   virtual uint64_t current_pos();
367 public:
368   raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {}
369   ~raw_svector_ostream();
370
371   /// tell - Return the current offset with the stream.
372   uint64_t tell();
373 };
374
375 } // end llvm namespace
376
377 #endif