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/Support/Compiler.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 &) LLVM_DELETED_FUNCTION; 42 raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION; 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. tell()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. SetBufferSize(size_t Size)105 void SetBufferSize(size_t Size) { 106 flush(); 107 SetBufferAndMode(new char[Size], Size, InternalBuffer); 108 } 109 GetBufferSize()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. SetUnbuffered()124 void SetUnbuffered() { 125 flush(); 126 SetBufferAndMode(nullptr, 0, Unbuffered); 127 } 128 GetNumBytesInBuffer()129 size_t GetNumBytesInBuffer() const { 130 return OutBufCur - OutBufStart; 131 } 132 133 //===--------------------------------------------------------------------===// 134 // Data Output Interface 135 //===--------------------------------------------------------------------===// 136 flush()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<<(unsigned long N); 189 raw_ostream &operator<<(long N); 190 raw_ostream &operator<<(unsigned long long N); 191 raw_ostream &operator<<(long long N); 192 raw_ostream &operator<<(const void *P); 193 raw_ostream &operator<<(unsigned int N) { 194 return this->operator<<(static_cast<unsigned long>(N)); 195 } 196 197 raw_ostream &operator<<(int N) { 198 return this->operator<<(static_cast<long>(N)); 199 } 200 201 raw_ostream &operator<<(double N); 202 203 /// write_hex - Output \p N in hexadecimal, without any prefix or padding. 204 raw_ostream &write_hex(unsigned long long N); 205 206 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and 207 /// anything that doesn't satisfy std::isprint into an escape sequence. 208 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false); 209 210 raw_ostream &write(unsigned char C); 211 raw_ostream &write(const char *Ptr, size_t Size); 212 213 // Formatted output, see the format() function in Support/Format.h. 214 raw_ostream &operator<<(const format_object_base &Fmt); 215 216 // Formatted output, see the leftJustify() function in Support/Format.h. 217 raw_ostream &operator<<(const FormattedString &); 218 219 // Formatted output, see the formatHex() function in Support/Format.h. 220 raw_ostream &operator<<(const FormattedNumber &); 221 222 /// indent - Insert 'NumSpaces' spaces. 223 raw_ostream &indent(unsigned NumSpaces); 224 225 226 /// Changes the foreground color of text that will be output from this point 227 /// forward. 228 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to 229 /// change only the bold attribute, and keep colors untouched 230 /// @param Bold bold/brighter text, default false 231 /// @param BG if true change the background, default: change foreground 232 /// @returns itself so it can be used within << invocations 233 virtual raw_ostream &changeColor(enum Colors Color, 234 bool Bold = false, 235 bool BG = false) { 236 (void)Color; 237 (void)Bold; 238 (void)BG; 239 return *this; 240 } 241 242 /// Resets the colors to terminal defaults. Call this when you are done 243 /// outputting colored text, or before program exit. resetColor()244 virtual raw_ostream &resetColor() { return *this; } 245 246 /// Reverses the forground and background colors. reverseColor()247 virtual raw_ostream &reverseColor() { return *this; } 248 249 /// This function determines if this stream is connected to a "tty" or 250 /// "console" window. That is, the output would be displayed to the user 251 /// rather than being put on a pipe or stored in a file. is_displayed()252 virtual bool is_displayed() const { return false; } 253 254 /// This function determines if this stream is displayed and supports colors. has_colors()255 virtual bool has_colors() const { return is_displayed(); } 256 257 //===--------------------------------------------------------------------===// 258 // Subclass Interface 259 //===--------------------------------------------------------------------===// 260 261 private: 262 /// write_impl - The is the piece of the class that is implemented 263 /// by subclasses. This writes the \p Size bytes starting at 264 /// \p Ptr to the underlying stream. 265 /// 266 /// This function is guaranteed to only be called at a point at which it is 267 /// safe for the subclass to install a new buffer via SetBuffer. 268 /// 269 /// \param Ptr The start of the data to be written. For buffered streams this 270 /// is guaranteed to be the start of the buffer. 271 /// 272 /// \param Size The number of bytes to be written. 273 /// 274 /// \invariant { Size > 0 } 275 virtual void write_impl(const char *Ptr, size_t Size) = 0; 276 277 // An out of line virtual method to provide a home for the class vtable. 278 virtual void handle(); 279 280 /// current_pos - Return the current position within the stream, not 281 /// counting the bytes currently in the buffer. 282 virtual uint64_t current_pos() const = 0; 283 284 protected: 285 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is 286 /// intended for use only by subclasses which can arrange for the output to go 287 /// directly into the desired output buffer, instead of being copied on each 288 /// flush. SetBuffer(char * BufferStart,size_t Size)289 void SetBuffer(char *BufferStart, size_t Size) { 290 SetBufferAndMode(BufferStart, Size, ExternalBuffer); 291 } 292 293 /// preferred_buffer_size - Return an efficient buffer size for the 294 /// underlying output mechanism. 295 virtual size_t preferred_buffer_size() const; 296 297 /// getBufferStart - Return the beginning of the current stream buffer, or 0 298 /// if the stream is unbuffered. getBufferStart()299 const char *getBufferStart() const { return OutBufStart; } 300 301 //===--------------------------------------------------------------------===// 302 // Private Interface 303 //===--------------------------------------------------------------------===// 304 private: 305 /// SetBufferAndMode - Install the given buffer and mode. 306 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode); 307 308 /// flush_nonempty - Flush the current buffer, which is known to be 309 /// non-empty. This outputs the currently buffered data and resets 310 /// the buffer to empty. 311 void flush_nonempty(); 312 313 /// copy_to_buffer - Copy data into the buffer. Size must not be 314 /// greater than the number of unused bytes in the buffer. 315 void copy_to_buffer(const char *Ptr, size_t Size); 316 }; 317 318 //===----------------------------------------------------------------------===// 319 // File Output Streams 320 //===----------------------------------------------------------------------===// 321 322 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor. 323 /// 324 class raw_fd_ostream : public raw_ostream { 325 int FD; 326 bool ShouldClose; 327 328 /// Error This flag is true if an error of any kind has been detected. 329 /// 330 bool Error; 331 332 /// Controls whether the stream should attempt to use atomic writes, when 333 /// possible. 334 bool UseAtomicWrites; 335 336 uint64_t pos; 337 338 /// write_impl - See raw_ostream::write_impl. 339 void write_impl(const char *Ptr, size_t Size) override; 340 341 /// current_pos - Return the current position within the stream, not 342 /// counting the bytes currently in the buffer. current_pos()343 uint64_t current_pos() const override { return pos; } 344 345 /// preferred_buffer_size - Determine an efficient buffer size. 346 size_t preferred_buffer_size() const override; 347 348 /// error_detected - Set the flag indicating that an output error has 349 /// been encountered. error_detected()350 void error_detected() { Error = true; } 351 352 public: 353 /// Open the specified file for writing. If an error occurs, information 354 /// about the error is put into EC, and the stream should be immediately 355 /// destroyed; 356 /// \p Flags allows optional flags to control how the file will be opened. 357 /// 358 /// As a special case, if Filename is "-", then the stream will use 359 /// STDOUT_FILENO instead of opening a file. Note that it will still consider 360 /// itself to own the file descriptor. In particular, it will close the 361 /// file descriptor when it is done (this is necessary to detect 362 /// output errors). 363 raw_fd_ostream(StringRef Filename, std::error_code &EC, 364 sys::fs::OpenFlags Flags); 365 366 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If 367 /// ShouldClose is true, this closes the file when the stream is destroyed. 368 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false); 369 370 ~raw_fd_ostream(); 371 372 /// close - Manually flush the stream and close the file. 373 /// Note that this does not call fsync. 374 void close(); 375 376 /// seek - Flushes the stream and repositions the underlying file descriptor 377 /// position to the offset specified from the beginning of the file. 378 uint64_t seek(uint64_t off); 379 380 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for 381 /// individual output routines where possible. 382 /// 383 /// Note that because raw_ostream's are typically buffered, this flag is only 384 /// sensible when used on unbuffered streams which will flush their output 385 /// immediately. SetUseAtomicWrites(bool Value)386 void SetUseAtomicWrites(bool Value) { 387 UseAtomicWrites = Value; 388 } 389 390 raw_ostream &changeColor(enum Colors colors, bool bold=false, 391 bool bg=false) override; 392 raw_ostream &resetColor() override; 393 394 raw_ostream &reverseColor() override; 395 396 bool is_displayed() const override; 397 398 bool has_colors() const override; 399 400 /// has_error - Return the value of the flag in this raw_fd_ostream indicating 401 /// whether an output error has been encountered. 402 /// This doesn't implicitly flush any pending output. Also, it doesn't 403 /// guarantee to detect all errors unless the stream has been closed. has_error()404 bool has_error() const { 405 return Error; 406 } 407 408 /// clear_error - Set the flag read by has_error() to false. If the error 409 /// flag is set at the time when this raw_ostream's destructor is called, 410 /// report_fatal_error is called to report the error. Use clear_error() 411 /// after handling the error to avoid this behavior. 412 /// 413 /// "Errors should never pass silently. 414 /// Unless explicitly silenced." 415 /// - from The Zen of Python, by Tim Peters 416 /// clear_error()417 void clear_error() { 418 Error = false; 419 } 420 }; 421 422 /// outs() - This returns a reference to a raw_ostream for standard output. 423 /// Use it like: outs() << "foo" << "bar"; 424 raw_ostream &outs(); 425 426 /// errs() - This returns a reference to a raw_ostream for standard error. 427 /// Use it like: errs() << "foo" << "bar"; 428 raw_ostream &errs(); 429 430 /// nulls() - This returns a reference to a raw_ostream which simply discards 431 /// output. 432 raw_ostream &nulls(); 433 434 //===----------------------------------------------------------------------===// 435 // Output Stream Adaptors 436 //===----------------------------------------------------------------------===// 437 438 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a 439 /// simple adaptor class. This class does not encounter output errors. 440 class raw_string_ostream : public raw_ostream { 441 std::string &OS; 442 443 /// write_impl - See raw_ostream::write_impl. 444 void write_impl(const char *Ptr, size_t Size) override; 445 446 /// current_pos - Return the current position within the stream, not 447 /// counting the bytes currently in the buffer. current_pos()448 uint64_t current_pos() const override { return OS.size(); } 449 public: raw_string_ostream(std::string & O)450 explicit raw_string_ostream(std::string &O) : OS(O) {} 451 ~raw_string_ostream(); 452 453 /// str - Flushes the stream contents to the target string and returns 454 /// the string's reference. str()455 std::string& str() { 456 flush(); 457 return OS; 458 } 459 }; 460 461 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or 462 /// SmallString. This is a simple adaptor class. This class does not 463 /// encounter output errors. 464 class raw_svector_ostream : public raw_ostream { 465 SmallVectorImpl<char> &OS; 466 467 /// write_impl - See raw_ostream::write_impl. 468 void write_impl(const char *Ptr, size_t Size) override; 469 470 /// current_pos - Return the current position within the stream, not 471 /// counting the bytes currently in the buffer. 472 uint64_t current_pos() const override; 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: raw_null_ostream()501 explicit raw_null_ostream() {} 502 ~raw_null_ostream(); 503 }; 504 505 } // end llvm namespace 506 507 #endif 508