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