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