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