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