raw_ostream: << operator for callables with raw_stream argument
[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/DataTypes.h"
20 #include <functional>
21 #include <system_error>
22
23 namespace llvm {
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
27 class raw_ostream;
28 template <typename T> class SmallVectorImpl;
29
30 namespace sys {
31 namespace fs {
32 enum OpenFlags : unsigned;
33 }
34 }
35
36 /// Type of function that prints to raw_ostream.
37 ///
38 /// Typical usage:
39 ///     Printable PrintFoo(Foo x) {
40 ///       return [] (raw_ostream &os) { os << /* ... */; };
41 ///     }
42 ///     os << "Foo: " << PrintFoo(foo) << '\n';
43 typedef std::function<void(raw_ostream&)> Printable;
44
45 /// This class implements an extremely fast bulk output stream that can *only*
46 /// output to a stream.  It does not support seeking, reopening, rewinding, line
47 /// buffered disciplines etc. It is a simple buffer that outputs
48 /// a chunk at a time.
49 class raw_ostream {
50 private:
51   void operator=(const raw_ostream &) = delete;
52   raw_ostream(const raw_ostream &) = delete;
53
54   /// The buffer is handled in such a way that the buffer is
55   /// uninitialized, unbuffered, or out of space when OutBufCur >=
56   /// OutBufEnd. Thus a single comparison suffices to determine if we
57   /// need to take the slow path to write a single character.
58   ///
59   /// The buffer is in one of three states:
60   ///  1. Unbuffered (BufferMode == Unbuffered)
61   ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
62   ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
63   ///               OutBufEnd - OutBufStart >= 1).
64   ///
65   /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
66   /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
67   /// managed by the subclass.
68   ///
69   /// If a subclass installs an external buffer using SetBuffer then it can wait
70   /// for a \see write_impl() call to handle the data which has been put into
71   /// this buffer.
72   char *OutBufStart, *OutBufEnd, *OutBufCur;
73
74   enum BufferKind {
75     Unbuffered = 0,
76     InternalBuffer,
77     ExternalBuffer
78   } BufferMode;
79
80 public:
81   // color order matches ANSI escape sequence, don't change
82   enum Colors {
83     BLACK=0,
84     RED,
85     GREEN,
86     YELLOW,
87     BLUE,
88     MAGENTA,
89     CYAN,
90     WHITE,
91     SAVEDCOLOR
92   };
93
94   explicit raw_ostream(bool unbuffered = false)
95       : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
96     // Start out ready to flush.
97     OutBufStart = OutBufEnd = OutBufCur = nullptr;
98   }
99
100   virtual ~raw_ostream();
101
102   /// tell - Return the current offset with the file.
103   uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
104
105   //===--------------------------------------------------------------------===//
106   // Configuration Interface
107   //===--------------------------------------------------------------------===//
108
109   /// Set the stream to be buffered, with an automatically determined buffer
110   /// size.
111   void SetBuffered();
112
113   /// Set the stream to be buffered, using the specified buffer size.
114   void SetBufferSize(size_t Size) {
115     flush();
116     SetBufferAndMode(new char[Size], Size, InternalBuffer);
117   }
118
119   size_t GetBufferSize() const {
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 == nullptr)
123       return preferred_buffer_size();
124
125     // Otherwise just return the size of the allocated buffer.
126     return OutBufEnd - OutBufStart;
127   }
128
129   /// Set the stream to be unbuffered. When unbuffered, the stream will flush
130   /// after every write. This routine will also flush the buffer immediately
131   /// when the stream is being set to unbuffered.
132   void SetUnbuffered() {
133     flush();
134     SetBufferAndMode(nullptr, 0, Unbuffered);
135   }
136
137   size_t GetNumBytesInBuffer() const {
138     return OutBufCur - OutBufStart;
139   }
140
141   //===--------------------------------------------------------------------===//
142   // Data Output Interface
143   //===--------------------------------------------------------------------===//
144
145   void flush() {
146     if (OutBufCur != OutBufStart)
147       flush_nonempty();
148   }
149
150   raw_ostream &operator<<(char C) {
151     if (OutBufCur >= OutBufEnd)
152       return write(C);
153     *OutBufCur++ = C;
154     return *this;
155   }
156
157   raw_ostream &operator<<(unsigned char C) {
158     if (OutBufCur >= OutBufEnd)
159       return write(C);
160     *OutBufCur++ = C;
161     return *this;
162   }
163
164   raw_ostream &operator<<(signed char C) {
165     if (OutBufCur >= OutBufEnd)
166       return write(C);
167     *OutBufCur++ = C;
168     return *this;
169   }
170
171   raw_ostream &operator<<(StringRef Str) {
172     // Inline fast path, particularly for strings with a known length.
173     size_t Size = Str.size();
174
175     // Make sure we can use the fast path.
176     if (Size > (size_t)(OutBufEnd - OutBufCur))
177       return write(Str.data(), Size);
178
179     if (Size) {
180       memcpy(OutBufCur, Str.data(), Size);
181       OutBufCur += Size;
182     }
183     return *this;
184   }
185
186   raw_ostream &operator<<(const char *Str) {
187     // Inline fast path, particularly for constant strings where a sufficiently
188     // smart compiler will simplify strlen.
189
190     return this->operator<<(StringRef(Str));
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     return write(Str.data(), Str.length());
196   }
197
198   raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
199     return write(Str.data(), Str.size());
200   }
201
202   raw_ostream &operator<<(unsigned long N);
203   raw_ostream &operator<<(long N);
204   raw_ostream &operator<<(unsigned long long N);
205   raw_ostream &operator<<(long long N);
206   raw_ostream &operator<<(const void *P);
207   raw_ostream &operator<<(unsigned int N) {
208     return this->operator<<(static_cast<unsigned long>(N));
209   }
210
211   raw_ostream &operator<<(int N) {
212     return this->operator<<(static_cast<long>(N));
213   }
214
215   raw_ostream &operator<<(double N);
216
217   /// IO manipulator, \see Printable.
218   raw_ostream &operator<<(Printable P);
219
220   /// Output \p N in hexadecimal, without any prefix or padding.
221   raw_ostream &write_hex(unsigned long long N);
222
223   /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
224   /// satisfy std::isprint into an escape sequence.
225   raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
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   // Formatted output, see the leftJustify() function in Support/Format.h.
234   raw_ostream &operator<<(const FormattedString &);
235
236   // Formatted output, see the formatHex() function in Support/Format.h.
237   raw_ostream &operator<<(const FormattedNumber &);
238
239   /// indent - Insert 'NumSpaces' spaces.
240   raw_ostream &indent(unsigned NumSpaces);
241
242   /// Changes the foreground color of text that will be output from this point
243   /// forward.
244   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
245   /// change only the bold attribute, and keep colors untouched
246   /// @param Bold bold/brighter text, default false
247   /// @param BG if true change the background, default: change foreground
248   /// @returns itself so it can be used within << invocations
249   virtual raw_ostream &changeColor(enum Colors Color,
250                                    bool Bold = false,
251                                    bool BG = false) {
252     (void)Color;
253     (void)Bold;
254     (void)BG;
255     return *this;
256   }
257
258   /// Resets the colors to terminal defaults. Call this when you are done
259   /// outputting colored text, or before program exit.
260   virtual raw_ostream &resetColor() { return *this; }
261
262   /// Reverses the foreground and background colors.
263   virtual raw_ostream &reverseColor() { return *this; }
264
265   /// This function determines if this stream is connected to a "tty" or
266   /// "console" window. That is, the output would be displayed to the user
267   /// rather than being put on a pipe or stored in a file.
268   virtual bool is_displayed() const { return false; }
269
270   /// This function determines if this stream is displayed and supports colors.
271   virtual bool has_colors() const { return is_displayed(); }
272
273   //===--------------------------------------------------------------------===//
274   // Subclass Interface
275   //===--------------------------------------------------------------------===//
276
277 private:
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 /// An abstract base class for streams implementations that also support a
332 /// pwrite operation. This is useful for code that can mostly stream out data,
333 /// but needs to patch in a header that needs to know the output size.
334 class raw_pwrite_stream : public raw_ostream {
335   virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
336
337 public:
338   explicit raw_pwrite_stream(bool Unbuffered = false)
339       : raw_ostream(Unbuffered) {}
340   void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
341 #ifndef NDBEBUG
342     uint64_t Pos = tell();
343     // /dev/null always reports a pos of 0, so we cannot perform this check
344     // in that case.
345     if (Pos)
346       assert(Size + Offset <= Pos && "We don't support extending the stream");
347 #endif
348     pwrite_impl(Ptr, Size, Offset);
349   }
350 };
351
352 //===----------------------------------------------------------------------===//
353 // File Output Streams
354 //===----------------------------------------------------------------------===//
355
356 /// A raw_ostream that writes to a file descriptor.
357 ///
358 class raw_fd_ostream : public raw_pwrite_stream {
359   int FD;
360   bool ShouldClose;
361
362   /// Error This flag is true if an error of any kind has been detected.
363   ///
364   bool Error;
365
366   /// Controls whether the stream should attempt to use atomic writes, when
367   /// possible.
368   bool UseAtomicWrites;
369
370   uint64_t pos;
371
372   bool SupportsSeeking;
373
374   /// See raw_ostream::write_impl.
375   void write_impl(const char *Ptr, size_t Size) override;
376
377   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
378
379   /// Return the current position within the stream, not counting the bytes
380   /// currently in the buffer.
381   uint64_t current_pos() const override { return pos; }
382
383   /// Determine an efficient buffer size.
384   size_t preferred_buffer_size() const override;
385
386   /// Set the flag indicating that an output error has been encountered.
387   void error_detected() { Error = true; }
388
389 public:
390   /// Open the specified file for writing. If an error occurs, information
391   /// about the error is put into EC, and the stream should be immediately
392   /// destroyed;
393   /// \p Flags allows optional flags to control how the file will be opened.
394   ///
395   /// As a special case, if Filename is "-", then the stream will use
396   /// STDOUT_FILENO instead of opening a file. Note that it will still consider
397   /// itself to own the file descriptor. In particular, it will close the
398   /// file descriptor when it is done (this is necessary to detect
399   /// output errors).
400   raw_fd_ostream(StringRef Filename, std::error_code &EC,
401                  sys::fs::OpenFlags Flags);
402
403   /// FD is the file descriptor that this writes to.  If ShouldClose is true,
404   /// this closes the file when the stream is destroyed.
405   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
406
407   ~raw_fd_ostream() override;
408
409   /// Manually flush the stream and close the file. Note that this does not call
410   /// fsync.
411   void close();
412
413   bool supportsSeeking() { return SupportsSeeking; }
414
415   /// Flushes the stream and repositions the underlying file descriptor position
416   /// to the offset specified from the beginning of the file.
417   uint64_t seek(uint64_t off);
418
419   /// Set the stream to attempt to use atomic writes for individual output
420   /// routines where possible.
421   ///
422   /// Note that because raw_ostream's are typically buffered, this flag is only
423   /// sensible when used on unbuffered streams which will flush their output
424   /// immediately.
425   void SetUseAtomicWrites(bool Value) {
426     UseAtomicWrites = Value;
427   }
428
429   raw_ostream &changeColor(enum Colors colors, bool bold=false,
430                            bool bg=false) override;
431   raw_ostream &resetColor() override;
432
433   raw_ostream &reverseColor() override;
434
435   bool is_displayed() const override;
436
437   bool has_colors() const override;
438
439   /// Return the value of the flag in this raw_fd_ostream indicating whether an
440   /// output error has been encountered.
441   /// This doesn't implicitly flush any pending output.  Also, it doesn't
442   /// guarantee to detect all errors unless the stream has been closed.
443   bool has_error() const {
444     return Error;
445   }
446
447   /// Set the flag read by has_error() to false. If the error flag is set at the
448   /// time when this raw_ostream's destructor is called, report_fatal_error is
449   /// called to report the error. Use clear_error() after handling the error to
450   /// avoid this behavior.
451   ///
452   ///   "Errors should never pass silently.
453   ///    Unless explicitly silenced."
454   ///      - from The Zen of Python, by Tim Peters
455   ///
456   void clear_error() {
457     Error = false;
458   }
459 };
460
461 /// This returns a reference to a raw_ostream for standard output. Use it like:
462 /// outs() << "foo" << "bar";
463 raw_ostream &outs();
464
465 /// This returns a reference to a raw_ostream for standard error. Use it like:
466 /// errs() << "foo" << "bar";
467 raw_ostream &errs();
468
469 /// This returns a reference to a raw_ostream which simply discards output.
470 raw_ostream &nulls();
471
472 //===----------------------------------------------------------------------===//
473 // Output Stream Adaptors
474 //===----------------------------------------------------------------------===//
475
476 /// A raw_ostream that writes to an std::string.  This is a simple adaptor
477 /// class. This class does not encounter output errors.
478 class raw_string_ostream : public raw_ostream {
479   std::string &OS;
480
481   /// See raw_ostream::write_impl.
482   void write_impl(const char *Ptr, size_t Size) override;
483
484   /// Return the current position within the stream, not counting the bytes
485   /// currently in the buffer.
486   uint64_t current_pos() const override { return OS.size(); }
487
488 public:
489   explicit raw_string_ostream(std::string &O) : OS(O) {}
490   ~raw_string_ostream() override;
491
492   /// Flushes the stream contents to the target string and returns  the string's
493   /// reference.
494   std::string& str() {
495     flush();
496     return OS;
497   }
498 };
499
500 /// A raw_ostream that writes to an SmallVector or SmallString.  This is a
501 /// simple adaptor class. This class does not encounter output errors.
502 /// raw_svector_ostream operates without a buffer, delegating all memory
503 /// management to the SmallString. Thus the SmallString is always up-to-date,
504 /// may be used directly and there is no need to call flush().
505 class raw_svector_ostream : public raw_pwrite_stream {
506   SmallVectorImpl<char> &OS;
507
508   /// See raw_ostream::write_impl.
509   void write_impl(const char *Ptr, size_t Size) override;
510
511   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
512
513   /// Return the current position within the stream.
514   uint64_t current_pos() const override;
515
516 public:
517   /// Construct a new raw_svector_ostream.
518   ///
519   /// \param O The vector to write to; this should generally have at least 128
520   /// bytes free to avoid any extraneous memory overhead.
521   explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
522     SetUnbuffered();
523   }
524   ~raw_svector_ostream() override {}
525
526   void flush() = delete;
527
528   /// Return a StringRef for the vector contents.
529   StringRef str() { return StringRef(OS.data(), OS.size()); }
530 };
531
532 /// A raw_ostream that discards all output.
533 class raw_null_ostream : public raw_pwrite_stream {
534   /// See raw_ostream::write_impl.
535   void write_impl(const char *Ptr, size_t size) override;
536   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
537
538   /// Return the current position within the stream, not counting the bytes
539   /// currently in the buffer.
540   uint64_t current_pos() const override;
541
542 public:
543   explicit raw_null_ostream() {}
544   ~raw_null_ostream() override;
545 };
546
547 class buffer_ostream : public raw_svector_ostream {
548   raw_ostream &OS;
549   SmallVector<char, 0> Buffer;
550
551 public:
552   buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
553   ~buffer_ostream() override { OS << str(); }
554 };
555
556 } // end llvm namespace
557
558 #endif // LLVM_SUPPORT_RAW_OSTREAM_H