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