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