Add classof implementations to the raw_ostream classes.
[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/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/DataTypes.h"
21 #include <system_error>
22
23 namespace llvm {
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
27 template <typename T> class SmallVectorImpl;
28
29 namespace sys {
30 namespace fs {
31 enum OpenFlags : unsigned;
32 }
33 }
34
35 /// This class implements an extremely fast bulk output stream that can *only*
36 /// output to a stream.  It does not support seeking, reopening, rewinding, line
37 /// buffered disciplines etc. It is a simple buffer that outputs
38 /// a chunk at a time.
39 class raw_ostream {
40 private:
41   void operator=(const raw_ostream &) = delete;
42   raw_ostream(const raw_ostream &) = delete;
43
44   /// The buffer is handled in such a way that the buffer is
45   /// uninitialized, unbuffered, or out of space when OutBufCur >=
46   /// OutBufEnd. Thus a single comparison suffices to determine if we
47   /// need to take the slow path to write a single character.
48   ///
49   /// The buffer is in one of three states:
50   ///  1. Unbuffered (BufferMode == Unbuffered)
51   ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
52   ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
53   ///               OutBufEnd - OutBufStart >= 1).
54   ///
55   /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
56   /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
57   /// managed by the subclass.
58   ///
59   /// If a subclass installs an external buffer using SetBuffer then it can wait
60   /// for a \see write_impl() call to handle the data which has been put into
61   /// this buffer.
62   char *OutBufStart, *OutBufEnd, *OutBufCur;
63
64   enum BufferKind {
65     Unbuffered = 0,
66     InternalBuffer,
67     ExternalBuffer
68   } BufferMode;
69
70 public:
71   enum StreamKind {
72     SK_FD,
73     SK_STRING,
74     SK_SVECTOR,
75     SK_NULL,
76     SK_STD_OS,
77     SK_CIRCULAR,
78     SK_FORMATTED,
79     SK_COUNTING
80   };
81
82   // color order matches ANSI escape sequence, don't change
83   enum Colors {
84     BLACK=0,
85     RED,
86     GREEN,
87     YELLOW,
88     BLUE,
89     MAGENTA,
90     CYAN,
91     WHITE,
92     SAVEDCOLOR
93   };
94
95   explicit raw_ostream(StreamKind Kind, bool unbuffered = false)
96       : BufferMode(unbuffered ? Unbuffered : InternalBuffer), Kind(Kind) {
97     // Start out ready to flush.
98     OutBufStart = OutBufEnd = OutBufCur = nullptr;
99   }
100
101   virtual ~raw_ostream();
102
103   /// tell - Return the current offset with the file.
104   uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
105
106   //===--------------------------------------------------------------------===//
107   // Configuration Interface
108   //===--------------------------------------------------------------------===//
109
110   /// Set the stream to be buffered, with an automatically determined buffer
111   /// size.
112   void SetBuffered();
113
114   /// Set the stream to be buffered, using the specified buffer size.
115   void SetBufferSize(size_t Size) {
116     flush();
117     SetBufferAndMode(new char[Size], Size, InternalBuffer);
118   }
119
120   size_t GetBufferSize() const {
121     // If we're supposed to be buffered but haven't actually gotten around
122     // to allocating the buffer yet, return the value that would be used.
123     if (BufferMode != Unbuffered && OutBufStart == nullptr)
124       return preferred_buffer_size();
125
126     // Otherwise just return the size of the allocated buffer.
127     return OutBufEnd - OutBufStart;
128   }
129
130   /// Set the stream to be unbuffered. When unbuffered, the stream will flush
131   /// after every write. This routine will also flush the buffer immediately
132   /// when the stream is being set to unbuffered.
133   void SetUnbuffered() {
134     flush();
135     SetBufferAndMode(nullptr, 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<<(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 (Size > (size_t)(OutBufEnd - OutBufCur))
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, particularly for constant strings where a sufficiently
187     // smart compiler will simplify strlen.
188
189     return this->operator<<(StringRef(Str));
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     return write(Str.data(), Str.length());
195   }
196
197   raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
198     return write(Str.data(), Str.size());
199   }
200
201   raw_ostream &operator<<(unsigned long N);
202   raw_ostream &operator<<(long N);
203   raw_ostream &operator<<(unsigned long long N);
204   raw_ostream &operator<<(long long N);
205   raw_ostream &operator<<(const void *P);
206   raw_ostream &operator<<(unsigned int N) {
207     return this->operator<<(static_cast<unsigned long>(N));
208   }
209
210   raw_ostream &operator<<(int N) {
211     return this->operator<<(static_cast<long>(N));
212   }
213
214   raw_ostream &operator<<(double N);
215
216   /// Output \p N in hexadecimal, without any prefix or padding.
217   raw_ostream &write_hex(unsigned long long N);
218
219   /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
220   /// satisfy std::isprint into an escape sequence.
221   raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
222
223   raw_ostream &write(unsigned char C);
224   raw_ostream &write(const char *Ptr, size_t Size);
225
226   // Formatted output, see the format() function in Support/Format.h.
227   raw_ostream &operator<<(const format_object_base &Fmt);
228
229   // Formatted output, see the leftJustify() function in Support/Format.h.
230   raw_ostream &operator<<(const FormattedString &);
231   
232   // Formatted output, see the formatHex() function in Support/Format.h.
233   raw_ostream &operator<<(const FormattedNumber &);
234   
235   /// indent - Insert 'NumSpaces' spaces.
236   raw_ostream &indent(unsigned NumSpaces);
237
238
239   /// Changes the foreground color of text that will be output from this point
240   /// forward.
241   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
242   /// change only the bold attribute, and keep colors untouched
243   /// @param Bold bold/brighter text, default false
244   /// @param BG if true change the background, default: change foreground
245   /// @returns itself so it can be used within << invocations
246   virtual raw_ostream &changeColor(enum Colors Color,
247                                    bool Bold = false,
248                                    bool BG = false) {
249     (void)Color;
250     (void)Bold;
251     (void)BG;
252     return *this;
253   }
254
255   /// Resets the colors to terminal defaults. Call this when you are done
256   /// outputting colored text, or before program exit.
257   virtual raw_ostream &resetColor() { return *this; }
258
259   /// Reverses the forground and background colors.
260   virtual raw_ostream &reverseColor() { return *this; }
261
262   /// This function determines if this stream is connected to a "tty" or
263   /// "console" window. That is, the output would be displayed to the user
264   /// rather than being put on a pipe or stored in a file.
265   virtual bool is_displayed() const { return false; }
266
267   /// This function determines if this stream is displayed and supports colors.
268   virtual bool has_colors() const { return is_displayed(); }
269
270   //===--------------------------------------------------------------------===//
271   // Subclass Interface
272   //===--------------------------------------------------------------------===//
273
274   StreamKind getKind() const { return Kind; }
275
276 private:
277   StreamKind Kind;
278   /// The is the piece of the class that is implemented by subclasses.  This
279   /// writes the \p Size bytes starting at
280   /// \p Ptr to the underlying stream.
281   ///
282   /// This function is guaranteed to only be called at a point at which it is
283   /// safe for the subclass to install a new buffer via SetBuffer.
284   ///
285   /// \param Ptr The start of the data to be written. For buffered streams this
286   /// is guaranteed to be the start of the buffer.
287   ///
288   /// \param Size The number of bytes to be written.
289   ///
290   /// \invariant { Size > 0 }
291   virtual void write_impl(const char *Ptr, size_t Size) = 0;
292
293   // An out of line virtual method to provide a home for the class vtable.
294   virtual void handle();
295
296   /// Return the current position within the stream, not counting the bytes
297   /// currently in the buffer.
298   virtual uint64_t current_pos() const = 0;
299
300 protected:
301   /// Use the provided buffer as the raw_ostream buffer. This is intended for
302   /// use only by subclasses which can arrange for the output to go directly
303   /// into the desired output buffer, instead of being copied on each flush.
304   void SetBuffer(char *BufferStart, size_t Size) {
305     SetBufferAndMode(BufferStart, Size, ExternalBuffer);
306   }
307
308   /// Return an efficient buffer size for the underlying output mechanism.
309   virtual size_t preferred_buffer_size() const;
310
311   /// Return the beginning of the current stream buffer, or 0 if the stream is
312   /// unbuffered.
313   const char *getBufferStart() const { return OutBufStart; }
314
315   //===--------------------------------------------------------------------===//
316   // Private Interface
317   //===--------------------------------------------------------------------===//
318 private:
319   /// Install the given buffer and mode.
320   void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
321
322   /// Flush the current buffer, which is known to be non-empty. This outputs the
323   /// currently buffered data and resets the buffer to empty.
324   void flush_nonempty();
325
326   /// Copy data into the buffer. Size must not be greater than the number of
327   /// unused bytes in the buffer.
328   void copy_to_buffer(const char *Ptr, size_t Size);
329 };
330
331 //===----------------------------------------------------------------------===//
332 // File Output Streams
333 //===----------------------------------------------------------------------===//
334
335 /// A raw_ostream that writes to a file descriptor.
336 ///
337 class raw_fd_ostream : public raw_ostream {
338   int FD;
339   bool ShouldClose;
340
341   /// Error This flag is true if an error of any kind has been detected.
342   ///
343   bool Error;
344
345   /// Controls whether the stream should attempt to use atomic writes, when
346   /// possible.
347   bool UseAtomicWrites;
348
349   uint64_t pos;
350
351   /// See raw_ostream::write_impl.
352   void write_impl(const char *Ptr, size_t Size) override;
353
354   /// Return the current position within the stream, not counting the bytes
355   /// currently in the buffer.
356   uint64_t current_pos() const override { return pos; }
357
358   /// Determine an efficient buffer size.
359   size_t preferred_buffer_size() const override;
360
361   /// Set the flag indicating that an output error has been encountered.
362   void error_detected() { Error = true; }
363
364 public:
365   /// Open the specified file for writing. If an error occurs, information
366   /// about the error is put into EC, and the stream should be immediately
367   /// destroyed;
368   /// \p Flags allows optional flags to control how the file will be opened.
369   ///
370   /// As a special case, if Filename is "-", then the stream will use
371   /// STDOUT_FILENO instead of opening a file. Note that it will still consider
372   /// itself to own the file descriptor. In particular, it will close the
373   /// file descriptor when it is done (this is necessary to detect
374   /// output errors).
375   raw_fd_ostream(StringRef Filename, std::error_code &EC,
376                  sys::fs::OpenFlags Flags);
377
378   /// FD is the file descriptor that this writes to.  If ShouldClose is true,
379   /// this closes the file when the stream is destroyed.
380   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
381
382   static bool classof(const raw_ostream *OS) { return OS->getKind() == SK_FD; }
383
384   ~raw_fd_ostream();
385
386   /// Manually flush the stream and close the file. Note that this does not call
387   /// fsync.
388   void close();
389
390   /// Flushes the stream and repositions the underlying file descriptor position
391   /// to the offset specified from the beginning of the file.
392   uint64_t seek(uint64_t off);
393
394   /// Set the stream to attempt to use atomic writes for individual output
395   /// routines where possible.
396   ///
397   /// Note that because raw_ostream's are typically buffered, this flag is only
398   /// sensible when used on unbuffered streams which will flush their output
399   /// immediately.
400   void SetUseAtomicWrites(bool Value) {
401     UseAtomicWrites = Value;
402   }
403
404   raw_ostream &changeColor(enum Colors colors, bool bold=false,
405                            bool bg=false) override;
406   raw_ostream &resetColor() override;
407
408   raw_ostream &reverseColor() override;
409
410   bool is_displayed() const override;
411
412   bool has_colors() const override;
413
414   /// Return the value of the flag in this raw_fd_ostream indicating whether an
415   /// output error has been encountered.
416   /// This doesn't implicitly flush any pending output.  Also, it doesn't
417   /// guarantee to detect all errors unless the stream has been closed.
418   bool has_error() const {
419     return Error;
420   }
421
422   /// Set the flag read by has_error() to false. If the error flag is set at the
423   /// time when this raw_ostream's destructor is called, report_fatal_error is
424   /// called to report the error. Use clear_error() after handling the error to
425   /// avoid this behavior.
426   ///
427   ///   "Errors should never pass silently.
428   ///    Unless explicitly silenced."
429   ///      - from The Zen of Python, by Tim Peters
430   ///
431   void clear_error() {
432     Error = false;
433   }
434 };
435
436 /// This returns a reference to a raw_ostream for standard output. Use it like:
437 /// outs() << "foo" << "bar";
438 raw_ostream &outs();
439
440 /// This returns a reference to a raw_ostream for standard error. Use it like:
441 /// errs() << "foo" << "bar";
442 raw_ostream &errs();
443
444 /// This returns a reference to a raw_ostream which simply discards output.
445 raw_ostream &nulls();
446
447 //===----------------------------------------------------------------------===//
448 // Output Stream Adaptors
449 //===----------------------------------------------------------------------===//
450
451 /// A raw_ostream that writes to an std::string.  This is a simple adaptor
452 /// class. This class does not encounter output errors.
453 class raw_string_ostream : public raw_ostream {
454   std::string &OS;
455
456   /// See raw_ostream::write_impl.
457   void write_impl(const char *Ptr, size_t Size) override;
458
459   /// Return the current position within the stream, not counting the bytes
460   /// currently in the buffer.
461   uint64_t current_pos() const override { return OS.size(); }
462 public:
463   explicit raw_string_ostream(std::string &O) : raw_ostream(SK_STRING), OS(O) {}
464   ~raw_string_ostream();
465
466   static bool classof(const raw_ostream *OS) {
467     return OS->getKind() == SK_STRING;
468   }
469
470   /// Flushes the stream contents to the target string and returns  the string's
471   /// reference.
472   std::string& str() {
473     flush();
474     return OS;
475   }
476 };
477
478 /// A raw_ostream that writes to an SmallVector or SmallString.  This is a
479 /// simple adaptor class. This class does not encounter output errors.
480 class raw_svector_ostream : public raw_ostream {
481   SmallVectorImpl<char> &OS;
482
483   /// See raw_ostream::write_impl.
484   void write_impl(const char *Ptr, size_t Size) override;
485
486   /// Return the current position within the stream, not counting the bytes
487   /// currently in the buffer.
488   uint64_t current_pos() const override;
489 public:
490   /// Construct a new raw_svector_ostream.
491   ///
492   /// \param O The vector to write to; this should generally have at least 128
493   /// bytes free to avoid any extraneous memory overhead.
494   explicit raw_svector_ostream(SmallVectorImpl<char> &O);
495   ~raw_svector_ostream();
496
497   static bool classof(const raw_ostream *OS) {
498     return OS->getKind() == SK_SVECTOR;
499   }
500
501   /// This is called when the SmallVector we're appending to is changed outside
502   /// of the raw_svector_ostream's control.  It is only safe to do this if the
503   /// raw_svector_ostream has previously been flushed.
504   void resync();
505
506   /// Flushes the stream contents to the target vector and return a StringRef
507   /// for the vector contents.
508   StringRef str();
509 };
510
511 /// A raw_ostream that discards all output.
512 class raw_null_ostream : public raw_ostream {
513   /// See raw_ostream::write_impl.
514   void write_impl(const char *Ptr, size_t size) override;
515
516   /// Return the current position within the stream, not counting the bytes
517   /// currently in the buffer.
518   uint64_t current_pos() const override;
519
520 public:
521   explicit raw_null_ostream() : raw_ostream(SK_NULL) {}
522   ~raw_null_ostream();
523   static bool classof(const raw_ostream *OS) {
524     return OS->getKind() == SK_NULL;
525   }
526 };
527
528 } // end llvm namespace
529
530 #endif