OSDN Git Service

df8de09b5814b34bcad46f1cd8f05a9a69ad7afb
[android-x86/external-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 <system_error>
21
22 namespace llvm {
23 class formatv_object_base;
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
27 class FormattedBytes;
28 template <typename T> class SmallVectorImpl;
29
30 namespace sys {
31 namespace fs {
32 enum OpenFlags : unsigned;
33 }
34 }
35
36 /// This class implements an extremely fast bulk output stream that can *only*
37 /// output to a stream.  It does not support seeking, reopening, rewinding, line
38 /// 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   /// Set the stream to be buffered, with an automatically determined buffer
101   /// size.
102   void SetBuffered();
103
104   /// Set the stream to be buffered, using the specified buffer size.
105   void SetBufferSize(size_t Size) {
106     flush();
107     SetBufferAndMode(new char[Size], Size, InternalBuffer);
108   }
109
110   size_t GetBufferSize() const {
111     // If we're supposed to be buffered but haven't actually gotten around
112     // to allocating the buffer yet, return the value that would be used.
113     if (BufferMode != Unbuffered && OutBufStart == nullptr)
114       return preferred_buffer_size();
115
116     // Otherwise just return the size of the allocated buffer.
117     return OutBufEnd - OutBufStart;
118   }
119
120   /// Set the stream to be unbuffered. When unbuffered, the stream will flush
121   /// after every write. This routine will also flush the buffer immediately
122   /// when the stream is being set to unbuffered.
123   void SetUnbuffered() {
124     flush();
125     SetBufferAndMode(nullptr, 0, Unbuffered);
126   }
127
128   size_t GetNumBytesInBuffer() const {
129     return OutBufCur - OutBufStart;
130   }
131
132   //===--------------------------------------------------------------------===//
133   // Data Output Interface
134   //===--------------------------------------------------------------------===//
135
136   void flush() {
137     if (OutBufCur != OutBufStart)
138       flush_nonempty();
139   }
140
141   raw_ostream &operator<<(char C) {
142     if (OutBufCur >= OutBufEnd)
143       return write(C);
144     *OutBufCur++ = C;
145     return *this;
146   }
147
148   raw_ostream &operator<<(unsigned char C) {
149     if (OutBufCur >= OutBufEnd)
150       return write(C);
151     *OutBufCur++ = C;
152     return *this;
153   }
154
155   raw_ostream &operator<<(signed char C) {
156     if (OutBufCur >= OutBufEnd)
157       return write(C);
158     *OutBufCur++ = C;
159     return *this;
160   }
161
162   raw_ostream &operator<<(StringRef Str) {
163     // Inline fast path, particularly for strings with a known length.
164     size_t Size = Str.size();
165
166     // Make sure we can use the fast path.
167     if (Size > (size_t)(OutBufEnd - OutBufCur))
168       return write(Str.data(), Size);
169
170     if (Size) {
171       memcpy(OutBufCur, Str.data(), Size);
172       OutBufCur += Size;
173     }
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   /// Output \p N in hexadecimal, without any prefix or padding.
209   raw_ostream &write_hex(unsigned long long N);
210
211   /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
212   /// 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   // Formatted output, see the formatv() function in Support/FormatVariadic.h.
228   raw_ostream &operator<<(const formatv_object_base &);
229
230   // Formatted output, see the format_bytes() function in Support/Format.h.
231   raw_ostream &operator<<(const FormattedBytes &);
232
233   /// indent - Insert 'NumSpaces' spaces.
234   raw_ostream &indent(unsigned NumSpaces);
235
236   /// Changes the foreground color of text that will be output from this point
237   /// forward.
238   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
239   /// change only the bold attribute, and keep colors untouched
240   /// @param Bold bold/brighter text, default false
241   /// @param BG if true change the background, default: change foreground
242   /// @returns itself so it can be used within << invocations
243   virtual raw_ostream &changeColor(enum Colors Color,
244                                    bool Bold = false,
245                                    bool BG = false) {
246     (void)Color;
247     (void)Bold;
248     (void)BG;
249     return *this;
250   }
251
252   /// Resets the colors to terminal defaults. Call this when you are done
253   /// outputting colored text, or before program exit.
254   virtual raw_ostream &resetColor() { return *this; }
255
256   /// Reverses the foreground and background colors.
257   virtual raw_ostream &reverseColor() { return *this; }
258
259   /// This function determines if this stream is connected to a "tty" or
260   /// "console" window. That is, the output would be displayed to the user
261   /// rather than being put on a pipe or stored in a file.
262   virtual bool is_displayed() const { return false; }
263
264   /// This function determines if this stream is displayed and supports colors.
265   virtual bool has_colors() const { return is_displayed(); }
266
267   //===--------------------------------------------------------------------===//
268   // Subclass Interface
269   //===--------------------------------------------------------------------===//
270
271 private:
272   /// The is the piece of the class that is implemented by subclasses.  This
273   /// writes the \p Size bytes starting at
274   /// \p Ptr to the underlying stream.
275   ///
276   /// This function is guaranteed to only be called at a point at which it is
277   /// safe for the subclass to install a new buffer via SetBuffer.
278   ///
279   /// \param Ptr The start of the data to be written. For buffered streams this
280   /// is guaranteed to be the start of the buffer.
281   ///
282   /// \param Size The number of bytes to be written.
283   ///
284   /// \invariant { Size > 0 }
285   virtual void write_impl(const char *Ptr, size_t Size) = 0;
286
287   // An out of line virtual method to provide a home for the class vtable.
288   virtual void handle();
289
290   /// Return the current position within the stream, not counting the bytes
291   /// currently in the buffer.
292   virtual uint64_t current_pos() const = 0;
293
294 protected:
295   /// Use the provided buffer as the raw_ostream buffer. This is intended for
296   /// use only by subclasses which can arrange for the output to go directly
297   /// into the desired output buffer, instead of being copied on each flush.
298   void SetBuffer(char *BufferStart, size_t Size) {
299     SetBufferAndMode(BufferStart, Size, ExternalBuffer);
300   }
301
302   /// Return an efficient buffer size for the underlying output mechanism.
303   virtual size_t preferred_buffer_size() const;
304
305   /// Return the beginning of the current stream buffer, or 0 if the stream is
306   /// unbuffered.
307   const char *getBufferStart() const { return OutBufStart; }
308
309   //===--------------------------------------------------------------------===//
310   // Private Interface
311   //===--------------------------------------------------------------------===//
312 private:
313   /// Install the given buffer and mode.
314   void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
315
316   /// Flush the current buffer, which is known to be non-empty. This outputs the
317   /// currently buffered data and resets the buffer to empty.
318   void flush_nonempty();
319
320   /// Copy data into the buffer. Size must not be greater than the number of
321   /// unused bytes in the buffer.
322   void copy_to_buffer(const char *Ptr, size_t Size);
323 };
324
325 /// An abstract base class for streams implementations that also support a
326 /// pwrite operation. This is useful for code that can mostly stream out data,
327 /// but needs to patch in a header that needs to know the output size.
328 class raw_pwrite_stream : public raw_ostream {
329   virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
330
331 public:
332   explicit raw_pwrite_stream(bool Unbuffered = false)
333       : raw_ostream(Unbuffered) {}
334   void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
335 #ifndef NDBEBUG
336     uint64_t Pos = tell();
337     // /dev/null always reports a pos of 0, so we cannot perform this check
338     // in that case.
339     if (Pos)
340       assert(Size + Offset <= Pos && "We don't support extending the stream");
341 #endif
342     pwrite_impl(Ptr, Size, Offset);
343   }
344 };
345
346 //===----------------------------------------------------------------------===//
347 // File Output Streams
348 //===----------------------------------------------------------------------===//
349
350 /// A raw_ostream that writes to a file descriptor.
351 ///
352 class raw_fd_ostream : public raw_pwrite_stream {
353   int FD;
354   bool ShouldClose;
355
356   /// Error This flag is true if an error of any kind has been detected.
357   ///
358   bool Error;
359
360   uint64_t pos;
361
362   bool SupportsSeeking;
363
364   /// See raw_ostream::write_impl.
365   void write_impl(const char *Ptr, size_t Size) override;
366
367   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
368
369   /// Return the current position within the stream, not counting the bytes
370   /// currently in the buffer.
371   uint64_t current_pos() const override { return pos; }
372
373   /// Determine an efficient buffer size.
374   size_t preferred_buffer_size() const override;
375
376   /// Set the flag indicating that an output error has been encountered.
377   void error_detected() { Error = true; }
378
379 public:
380   /// Open the specified file for writing. If an error occurs, information
381   /// about the error is put into EC, and the stream should be immediately
382   /// destroyed;
383   /// \p Flags allows optional flags to control how the file will be opened.
384   ///
385   /// As a special case, if Filename is "-", then the stream will use
386   /// STDOUT_FILENO instead of opening a file. Note that it will still consider
387   /// itself to own the file descriptor. In particular, it will close the
388   /// file descriptor when it is done (this is necessary to detect
389   /// output errors).
390   raw_fd_ostream(StringRef Filename, std::error_code &EC,
391                  sys::fs::OpenFlags Flags);
392
393   /// FD is the file descriptor that this writes to.  If ShouldClose is true,
394   /// this closes the file when the stream is destroyed.
395   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
396
397   ~raw_fd_ostream() override;
398
399   /// Manually flush the stream and close the file. Note that this does not call
400   /// fsync.
401   void close();
402
403   bool supportsSeeking() { return SupportsSeeking; }
404
405   /// Flushes the stream and repositions the underlying file descriptor position
406   /// to the offset specified from the beginning of the file.
407   uint64_t seek(uint64_t off);
408
409   raw_ostream &changeColor(enum Colors colors, bool bold=false,
410                            bool bg=false) override;
411   raw_ostream &resetColor() override;
412
413   raw_ostream &reverseColor() override;
414
415   bool is_displayed() const override;
416
417   bool has_colors() const override;
418
419   /// Return the value of the flag in this raw_fd_ostream indicating whether an
420   /// output error has been encountered.
421   /// This doesn't implicitly flush any pending output.  Also, it doesn't
422   /// guarantee to detect all errors unless the stream has been closed.
423   bool has_error() const {
424     return Error;
425   }
426
427   /// Set the flag read by has_error() to false. If the error flag is set at the
428   /// time when this raw_ostream's destructor is called, report_fatal_error is
429   /// called to report the error. Use clear_error() after handling the error to
430   /// avoid this behavior.
431   ///
432   ///   "Errors should never pass silently.
433   ///    Unless explicitly silenced."
434   ///      - from The Zen of Python, by Tim Peters
435   ///
436   void clear_error() {
437     Error = false;
438   }
439 };
440
441 /// This returns a reference to a raw_ostream for standard output. Use it like:
442 /// outs() << "foo" << "bar";
443 raw_ostream &outs();
444
445 /// This returns a reference to a raw_ostream for standard error. Use it like:
446 /// errs() << "foo" << "bar";
447 raw_ostream &errs();
448
449 /// This returns a reference to a raw_ostream which simply discards output.
450 raw_ostream &nulls();
451
452 //===----------------------------------------------------------------------===//
453 // Output Stream Adaptors
454 //===----------------------------------------------------------------------===//
455
456 /// A raw_ostream that writes to an std::string.  This is a simple adaptor
457 /// class. This class does not encounter output errors.
458 class raw_string_ostream : public raw_ostream {
459   std::string &OS;
460
461   /// See raw_ostream::write_impl.
462   void write_impl(const char *Ptr, size_t Size) override;
463
464   /// Return the current position within the stream, not counting the bytes
465   /// currently in the buffer.
466   uint64_t current_pos() const override { return OS.size(); }
467
468 public:
469   explicit raw_string_ostream(std::string &O) : OS(O) {}
470   ~raw_string_ostream() override;
471
472   /// Flushes the stream contents to the target string and returns  the string's
473   /// reference.
474   std::string& str() {
475     flush();
476     return OS;
477   }
478 };
479
480 /// A raw_ostream that writes to an SmallVector or SmallString.  This is a
481 /// simple adaptor class. This class does not encounter output errors.
482 /// raw_svector_ostream operates without a buffer, delegating all memory
483 /// management to the SmallString. Thus the SmallString is always up-to-date,
484 /// may be used directly and there is no need to call flush().
485 class raw_svector_ostream : public raw_pwrite_stream {
486   SmallVectorImpl<char> &OS;
487
488   /// See raw_ostream::write_impl.
489   void write_impl(const char *Ptr, size_t Size) override;
490
491   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
492
493   /// Return the current position within the stream.
494   uint64_t current_pos() const override;
495
496 public:
497   /// Construct a new raw_svector_ostream.
498   ///
499   /// \param O The vector to write to; this should generally have at least 128
500   /// bytes free to avoid any extraneous memory overhead.
501   explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
502     SetUnbuffered();
503   }
504   ~raw_svector_ostream() override {}
505
506   void flush() = delete;
507
508   /// Return a StringRef for the vector contents.
509   StringRef str() { return StringRef(OS.data(), OS.size()); }
510 };
511
512 /// A raw_ostream that discards all output.
513 class raw_null_ostream : public raw_pwrite_stream {
514   /// See raw_ostream::write_impl.
515   void write_impl(const char *Ptr, size_t size) override;
516   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
517
518   /// Return the current position within the stream, not counting the bytes
519   /// currently in the buffer.
520   uint64_t current_pos() const override;
521
522 public:
523   explicit raw_null_ostream() {}
524   ~raw_null_ostream() override;
525 };
526
527 class buffer_ostream : public raw_svector_ostream {
528   raw_ostream &OS;
529   SmallVector<char, 0> Buffer;
530
531 public:
532   buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
533   ~buffer_ostream() override { OS << str(); }
534 };
535
536 } // end llvm namespace
537
538 #endif // LLVM_SUPPORT_RAW_OSTREAM_H