raw_ostream.h revision 8316f2d3810dd37bae0f847bc3efd495432b5893
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/System/DataTypes.h"
19
20namespace llvm {
21  class format_object_base;
22  template <typename T>
23  class SmallVectorImpl;
24
25/// raw_ostream - This class implements an extremely fast bulk output stream
26/// that can *only* output to a stream.  It does not support seeking, reopening,
27/// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
28/// a chunk at a time.
29class raw_ostream {
30private:
31  // Do not implement. raw_ostream is noncopyable.
32  void operator=(const raw_ostream &);
33  raw_ostream(const raw_ostream &);
34
35  /// The buffer is handled in such a way that the buffer is
36  /// uninitialized, unbuffered, or out of space when OutBufCur >=
37  /// OutBufEnd. Thus a single comparison suffices to determine if we
38  /// need to take the slow path to write a single character.
39  ///
40  /// The buffer is in one of three states:
41  ///  1. Unbuffered (BufferMode == Unbuffered)
42  ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
43  ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
44  ///               OutBufEnd - OutBufStart >= 1).
45  ///
46  /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
47  /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
48  /// managed by the subclass.
49  ///
50  /// If a subclass installs an external buffer using SetBuffer then it can wait
51  /// for a \see write_impl() call to handle the data which has been put into
52  /// this buffer.
53  char *OutBufStart, *OutBufEnd, *OutBufCur;
54
55  enum BufferKind {
56    Unbuffered = 0,
57    InternalBuffer,
58    ExternalBuffer
59  } BufferMode;
60
61  /// Error This flag is true if an error of any kind has been detected.
62  ///
63  bool Error;
64
65public:
66  // color order matches ANSI escape sequence, don't change
67  enum Colors {
68    BLACK=0,
69    RED,
70    GREEN,
71    YELLOW,
72    BLUE,
73    MAGENTA,
74    CYAN,
75    WHITE,
76    SAVEDCOLOR
77  };
78
79  explicit raw_ostream(bool unbuffered=false)
80    : BufferMode(unbuffered ? Unbuffered : InternalBuffer), Error(false) {
81    // Start out ready to flush.
82    OutBufStart = OutBufEnd = OutBufCur = 0;
83  }
84
85  virtual ~raw_ostream();
86
87  /// tell - Return the current offset with the file.
88  uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
89
90  /// has_error - Return the value of the flag in this raw_ostream indicating
91  /// whether an output error has been encountered.
92  /// This doesn't implicitly flush any pending output.
93  bool has_error() const {
94    return Error;
95  }
96
97  /// clear_error - Set the flag read by has_error() to false. If the error
98  /// flag is set at the time when this raw_ostream's destructor is called,
99  /// report_fatal_error is called to report the error. Use clear_error()
100  /// after handling the error to avoid this behavior.
101  void clear_error() {
102    Error = false;
103  }
104
105  //===--------------------------------------------------------------------===//
106  // Configuration Interface
107  //===--------------------------------------------------------------------===//
108
109  /// SetBuffered - Set the stream to be buffered, with an automatically
110  /// determined buffer size.
111  void SetBuffered();
112
113  /// SetBufferSize - Set the stream to be buffered, using the
114  /// specified buffer size.
115  void SetBufferSize(size_t Size) {
116    flush();
117    SetBufferAndMode(new char[Size], Size, InternalBuffer);
118  }
119
120  size_t GetBufferSize() const {
121    // If we're supposed to be buffered but haven't actually gotten around
122    // to allocating the buffer yet, return the value that would be used.
123    if (BufferMode != Unbuffered && OutBufStart == 0)
124      return preferred_buffer_size();
125
126    // Otherwise just return the size of the allocated buffer.
127    return OutBufEnd - OutBufStart;
128  }
129
130  /// SetUnbuffered - Set the stream to be unbuffered. When
131  /// unbuffered, the stream will flush after every write. This routine
132  /// will also flush the buffer immediately when the stream is being
133  /// set to unbuffered.
134  void SetUnbuffered() {
135    flush();
136    SetBufferAndMode(0, 0, Unbuffered);
137  }
138
139  size_t GetNumBytesInBuffer() const {
140    return OutBufCur - OutBufStart;
141  }
142
143  //===--------------------------------------------------------------------===//
144  // Data Output Interface
145  //===--------------------------------------------------------------------===//
146
147  void flush() {
148    if (OutBufCur != OutBufStart)
149      flush_nonempty();
150  }
151
152  raw_ostream &operator<<(char C) {
153    if (OutBufCur >= OutBufEnd)
154      return write(C);
155    *OutBufCur++ = C;
156    return *this;
157  }
158
159  raw_ostream &operator<<(unsigned char C) {
160    if (OutBufCur >= OutBufEnd)
161      return write(C);
162    *OutBufCur++ = C;
163    return *this;
164  }
165
166  raw_ostream &operator<<(signed char C) {
167    if (OutBufCur >= OutBufEnd)
168      return write(C);
169    *OutBufCur++ = C;
170    return *this;
171  }
172
173  raw_ostream &operator<<(StringRef Str) {
174    // Inline fast path, particularly for strings with a known length.
175    size_t Size = Str.size();
176
177    // Make sure we can use the fast path.
178    if (OutBufCur+Size > OutBufEnd)
179      return write(Str.data(), Size);
180
181    memcpy(OutBufCur, Str.data(), Size);
182    OutBufCur += Size;
183    return *this;
184  }
185
186  raw_ostream &operator<<(const char *Str) {
187    // Inline fast path, particulary 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<<(unsigned long N);
199  raw_ostream &operator<<(long N);
200  raw_ostream &operator<<(unsigned long long N);
201  raw_ostream &operator<<(long long N);
202  raw_ostream &operator<<(const void *P);
203  raw_ostream &operator<<(unsigned int N) {
204    return this->operator<<(static_cast<unsigned long>(N));
205  }
206
207  raw_ostream &operator<<(int N) {
208    return this->operator<<(static_cast<long>(N));
209  }
210
211  raw_ostream &operator<<(double N);
212
213  /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
214  raw_ostream &write_hex(unsigned long long N);
215
216  /// write_escaped - Output \arg Str, turning '\\', '\t', '\n', '"', and
217  /// anything that doesn't satisfy std::isprint into an escape sequence.
218  raw_ostream &write_escaped(StringRef Str);
219
220  raw_ostream &write(unsigned char C);
221  raw_ostream &write(const char *Ptr, size_t Size);
222
223  // Formatted output, see the format() function in Support/Format.h.
224  raw_ostream &operator<<(const format_object_base &Fmt);
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 colors 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, bool = false,
238				   bool = false) { return *this; }
239
240  /// Resets the colors to terminal defaults. Call this when you are done
241  /// outputting colored text, or before program exit.
242  virtual raw_ostream &resetColor() { return *this; }
243
244  /// This function determines if this stream is connected to a "tty" or
245  /// "console" window. That is, the output would be displayed to the user
246  /// rather than being put on a pipe or stored in a file.
247  virtual bool is_displayed() const { return false; }
248
249  //===--------------------------------------------------------------------===//
250  // Subclass Interface
251  //===--------------------------------------------------------------------===//
252
253private:
254  /// write_impl - The is the piece of the class that is implemented
255  /// by subclasses.  This writes the \args Size bytes starting at
256  /// \arg 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  /// \arg Ptr - The start of the data to be written. For buffered streams this
262  /// is guaranteed to be the start of the buffer.
263  /// \arg Size - The number of bytes to be written.
264  ///
265  /// \invariant { Size > 0 }
266  virtual void write_impl(const char *Ptr, size_t Size) = 0;
267
268  // An out of line virtual method to provide a home for the class vtable.
269  virtual void handle();
270
271  /// current_pos - Return the current position within the stream, not
272  /// counting the bytes currently in the buffer.
273  virtual uint64_t current_pos() const = 0;
274
275protected:
276  /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
277  /// intended for use only by subclasses which can arrange for the output to go
278  /// directly into the desired output buffer, instead of being copied on each
279  /// flush.
280  void SetBuffer(char *BufferStart, size_t Size) {
281    SetBufferAndMode(BufferStart, Size, ExternalBuffer);
282  }
283
284  /// preferred_buffer_size - Return an efficient buffer size for the
285  /// underlying output mechanism.
286  virtual size_t preferred_buffer_size() const;
287
288  /// error_detected - Set the flag indicating that an output error has
289  /// been encountered.
290  void error_detected() { Error = true; }
291
292  /// getBufferStart - Return the beginning of the current stream buffer, or 0
293  /// if the stream is unbuffered.
294  const char *getBufferStart() const { return OutBufStart; }
295
296  //===--------------------------------------------------------------------===//
297  // Private Interface
298  //===--------------------------------------------------------------------===//
299private:
300  /// SetBufferAndMode - Install the given buffer and mode.
301  void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
302
303  /// flush_nonempty - Flush the current buffer, which is known to be
304  /// non-empty. This outputs the currently buffered data and resets
305  /// the buffer to empty.
306  void flush_nonempty();
307
308  /// copy_to_buffer - Copy data into the buffer. Size must not be
309  /// greater than the number of unused bytes in the buffer.
310  void copy_to_buffer(const char *Ptr, size_t Size);
311};
312
313//===----------------------------------------------------------------------===//
314// File Output Streams
315//===----------------------------------------------------------------------===//
316
317/// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
318///
319class raw_fd_ostream : public raw_ostream {
320  int FD;
321  bool ShouldClose;
322  uint64_t pos;
323
324  /// write_impl - See raw_ostream::write_impl.
325  virtual void write_impl(const char *Ptr, size_t Size);
326
327  /// current_pos - Return the current position within the stream, not
328  /// counting the bytes currently in the buffer.
329  virtual uint64_t current_pos() const { return pos; }
330
331  /// preferred_buffer_size - Determine an efficient buffer size.
332  virtual size_t preferred_buffer_size() const;
333
334public:
335
336  enum {
337    /// F_Excl - When opening a file, this flag makes raw_fd_ostream
338    /// report an error if the file already exists.
339    F_Excl  = 1,
340
341    /// F_Append - When opening a file, if it already exists append to the
342    /// existing file instead of returning an error.  This may not be specified
343    /// with F_Excl.
344    F_Append = 2,
345
346    /// F_Binary - The file should be opened in binary mode on platforms that
347    /// make this distinction.
348    F_Binary = 4
349  };
350
351  /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
352  /// information about the error is put into ErrorInfo, and the stream should
353  /// be immediately destroyed; the string will be empty if no error occurred.
354  /// This allows optional flags to control how the file will be opened.
355  ///
356  /// \param Filename - The file to open. If this is "-" then the
357  /// stream will use stdout instead.
358  raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
359                 unsigned Flags = 0);
360
361  /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
362  /// ShouldClose is true, this closes the file when the stream is destroyed.
363  raw_fd_ostream(int fd, bool shouldClose,
364                 bool unbuffered=false) : raw_ostream(unbuffered), FD(fd),
365                                          ShouldClose(shouldClose) {}
366
367  ~raw_fd_ostream();
368
369  /// close - Manually flush the stream and close the file.
370  void close();
371
372  /// seek - Flushes the stream and repositions the underlying file descriptor
373  ///  positition to the offset specified from the beginning of the file.
374  uint64_t seek(uint64_t off);
375
376  virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
377                                   bool bg=false);
378  virtual raw_ostream &resetColor();
379
380  virtual bool is_displayed() const;
381};
382
383/// raw_stdout_ostream - This is a stream that always prints to stdout.
384///
385class raw_stdout_ostream : public raw_fd_ostream {
386  // An out of line virtual method to provide a home for the class vtable.
387  virtual void handle();
388public:
389  raw_stdout_ostream();
390};
391
392/// raw_stderr_ostream - This is a stream that always prints to stderr.
393///
394class raw_stderr_ostream : public raw_fd_ostream {
395  // An out of line virtual method to provide a home for the class vtable.
396  virtual void handle();
397public:
398  raw_stderr_ostream();
399};
400
401/// outs() - This returns a reference to a raw_ostream for standard output.
402/// Use it like: outs() << "foo" << "bar";
403raw_ostream &outs();
404
405/// errs() - This returns a reference to a raw_ostream for standard error.
406/// Use it like: errs() << "foo" << "bar";
407raw_ostream &errs();
408
409/// nulls() - This returns a reference to a raw_ostream which simply discards
410/// output.
411raw_ostream &nulls();
412
413//===----------------------------------------------------------------------===//
414// Output Stream Adaptors
415//===----------------------------------------------------------------------===//
416
417/// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
418/// simple adaptor class. This class does not encounter output errors.
419class raw_string_ostream : public raw_ostream {
420  std::string &OS;
421
422  /// write_impl - See raw_ostream::write_impl.
423  virtual void write_impl(const char *Ptr, size_t Size);
424
425  /// current_pos - Return the current position within the stream, not
426  /// counting the bytes currently in the buffer.
427  virtual uint64_t current_pos() const { return OS.size(); }
428public:
429  explicit raw_string_ostream(std::string &O) : OS(O) {}
430  ~raw_string_ostream();
431
432  /// str - Flushes the stream contents to the target string and returns
433  ///  the string's reference.
434  std::string& str() {
435    flush();
436    return OS;
437  }
438};
439
440/// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
441/// SmallString.  This is a simple adaptor class. This class does not
442/// encounter output errors.
443class raw_svector_ostream : public raw_ostream {
444  SmallVectorImpl<char> &OS;
445
446  /// write_impl - See raw_ostream::write_impl.
447  virtual void write_impl(const char *Ptr, size_t Size);
448
449  /// current_pos - Return the current position within the stream, not
450  /// counting the bytes currently in the buffer.
451  virtual uint64_t current_pos() const;
452public:
453  /// Construct a new raw_svector_ostream.
454  ///
455  /// \arg O - The vector to write to; this should generally have at least 128
456  /// bytes free to avoid any extraneous memory overhead.
457  explicit raw_svector_ostream(SmallVectorImpl<char> &O);
458  ~raw_svector_ostream();
459
460  /// resync - This is called when the SmallVector we're appending to is changed
461  /// outside of the raw_svector_ostream's control.  It is only safe to do this
462  /// if the raw_svector_ostream has previously been flushed.
463  void resync();
464
465  /// str - Flushes the stream contents to the target vector and return a
466  /// StringRef for the vector contents.
467  StringRef str();
468};
469
470/// raw_null_ostream - A raw_ostream that discards all output.
471class raw_null_ostream : public raw_ostream {
472  /// write_impl - See raw_ostream::write_impl.
473  virtual void write_impl(const char *Ptr, size_t size);
474
475  /// current_pos - Return the current position within the stream, not
476  /// counting the bytes currently in the buffer.
477  virtual uint64_t current_pos() const;
478
479public:
480  explicit raw_null_ostream() {}
481  ~raw_null_ostream();
482};
483
484} // end llvm namespace
485
486#endif
487