OSDN Git Service

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