raw_ostream.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the raw_ostream class.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
  18. #define LLVM_SUPPORT_RAW_OSTREAM_H
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/Support/DataTypes.h"
  23. #include <cassert>
  24. #include <cstddef>
  25. #include <cstdint>
  26. #include <cstring>
  27. #include <string>
  28. #if __cplusplus > 201402L
  29. #include <string_view>
  30. #endif
  31. #include <system_error>
  32. #include <type_traits>
  33. namespace llvm {
  34. class Duration;
  35. class formatv_object_base;
  36. class format_object_base;
  37. class FormattedString;
  38. class FormattedNumber;
  39. class FormattedBytes;
  40. template <class T> class LLVM_NODISCARD Expected;
  41. namespace sys {
  42. namespace fs {
  43. enum FileAccess : unsigned;
  44. enum OpenFlags : unsigned;
  45. enum CreationDisposition : unsigned;
  46. class FileLocker;
  47. } // end namespace fs
  48. } // end namespace sys
  49. /// This class implements an extremely fast bulk output stream that can *only*
  50. /// output to a stream. It does not support seeking, reopening, rewinding, line
  51. /// buffered disciplines etc. It is a simple buffer that outputs
  52. /// a chunk at a time.
  53. class raw_ostream {
  54. public:
  55. // Class kinds to support LLVM-style RTTI.
  56. enum class OStreamKind {
  57. OK_OStream,
  58. OK_FDStream,
  59. };
  60. private:
  61. OStreamKind Kind;
  62. /// The buffer is handled in such a way that the buffer is
  63. /// uninitialized, unbuffered, or out of space when OutBufCur >=
  64. /// OutBufEnd. Thus a single comparison suffices to determine if we
  65. /// need to take the slow path to write a single character.
  66. ///
  67. /// The buffer is in one of three states:
  68. /// 1. Unbuffered (BufferMode == Unbuffered)
  69. /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
  70. /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
  71. /// OutBufEnd - OutBufStart >= 1).
  72. ///
  73. /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
  74. /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
  75. /// managed by the subclass.
  76. ///
  77. /// If a subclass installs an external buffer using SetBuffer then it can wait
  78. /// for a \see write_impl() call to handle the data which has been put into
  79. /// this buffer.
  80. char *OutBufStart, *OutBufEnd, *OutBufCur;
  81. bool ColorEnabled = false;
  82. /// Optional stream this stream is tied to. If this stream is written to, the
  83. /// tied-to stream will be flushed first.
  84. raw_ostream *TiedStream = nullptr;
  85. enum class BufferKind {
  86. Unbuffered = 0,
  87. InternalBuffer,
  88. ExternalBuffer
  89. } BufferMode;
  90. public:
  91. // color order matches ANSI escape sequence, don't change
  92. enum class Colors {
  93. BLACK = 0,
  94. RED,
  95. GREEN,
  96. YELLOW,
  97. BLUE,
  98. MAGENTA,
  99. CYAN,
  100. WHITE,
  101. SAVEDCOLOR,
  102. RESET,
  103. };
  104. static constexpr Colors BLACK = Colors::BLACK;
  105. static constexpr Colors RED = Colors::RED;
  106. static constexpr Colors GREEN = Colors::GREEN;
  107. static constexpr Colors YELLOW = Colors::YELLOW;
  108. static constexpr Colors BLUE = Colors::BLUE;
  109. static constexpr Colors MAGENTA = Colors::MAGENTA;
  110. static constexpr Colors CYAN = Colors::CYAN;
  111. static constexpr Colors WHITE = Colors::WHITE;
  112. static constexpr Colors SAVEDCOLOR = Colors::SAVEDCOLOR;
  113. static constexpr Colors RESET = Colors::RESET;
  114. explicit raw_ostream(bool unbuffered = false,
  115. OStreamKind K = OStreamKind::OK_OStream)
  116. : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered
  117. : BufferKind::InternalBuffer) {
  118. // Start out ready to flush.
  119. OutBufStart = OutBufEnd = OutBufCur = nullptr;
  120. }
  121. raw_ostream(const raw_ostream &) = delete;
  122. void operator=(const raw_ostream &) = delete;
  123. virtual ~raw_ostream();
  124. /// tell - Return the current offset with the file.
  125. uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
  126. OStreamKind get_kind() const { return Kind; }
  127. //===--------------------------------------------------------------------===//
  128. // Configuration Interface
  129. //===--------------------------------------------------------------------===//
  130. /// If possible, pre-allocate \p ExtraSize bytes for stream data.
  131. /// i.e. it extends internal buffers to keep additional ExtraSize bytes.
  132. /// So that the stream could keep at least tell() + ExtraSize bytes
  133. /// without re-allocations. reserveExtraSpace() does not change
  134. /// the size/data of the stream.
  135. virtual void reserveExtraSpace(uint64_t ExtraSize) {}
  136. /// Set the stream to be buffered, with an automatically determined buffer
  137. /// size.
  138. void SetBuffered();
  139. /// Set the stream to be buffered, using the specified buffer size.
  140. void SetBufferSize(size_t Size) {
  141. flush();
  142. SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
  143. }
  144. size_t GetBufferSize() const {
  145. // If we're supposed to be buffered but haven't actually gotten around
  146. // to allocating the buffer yet, return the value that would be used.
  147. if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
  148. return preferred_buffer_size();
  149. // Otherwise just return the size of the allocated buffer.
  150. return OutBufEnd - OutBufStart;
  151. }
  152. /// Set the stream to be unbuffered. When unbuffered, the stream will flush
  153. /// after every write. This routine will also flush the buffer immediately
  154. /// when the stream is being set to unbuffered.
  155. void SetUnbuffered() {
  156. flush();
  157. SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
  158. }
  159. size_t GetNumBytesInBuffer() const {
  160. return OutBufCur - OutBufStart;
  161. }
  162. //===--------------------------------------------------------------------===//
  163. // Data Output Interface
  164. //===--------------------------------------------------------------------===//
  165. void flush() {
  166. if (OutBufCur != OutBufStart)
  167. flush_nonempty();
  168. }
  169. raw_ostream &operator<<(char C) {
  170. if (OutBufCur >= OutBufEnd)
  171. return write(C);
  172. *OutBufCur++ = C;
  173. return *this;
  174. }
  175. raw_ostream &operator<<(unsigned char C) {
  176. if (OutBufCur >= OutBufEnd)
  177. return write(C);
  178. *OutBufCur++ = C;
  179. return *this;
  180. }
  181. raw_ostream &operator<<(signed char C) {
  182. if (OutBufCur >= OutBufEnd)
  183. return write(C);
  184. *OutBufCur++ = C;
  185. return *this;
  186. }
  187. raw_ostream &operator<<(StringRef Str) {
  188. // Inline fast path, particularly for strings with a known length.
  189. size_t Size = Str.size();
  190. // Make sure we can use the fast path.
  191. if (Size > (size_t)(OutBufEnd - OutBufCur))
  192. return write(Str.data(), Size);
  193. if (Size) {
  194. memcpy(OutBufCur, Str.data(), Size);
  195. OutBufCur += Size;
  196. }
  197. return *this;
  198. }
  199. raw_ostream &operator<<(const char *Str) {
  200. // Inline fast path, particularly for constant strings where a sufficiently
  201. // smart compiler will simplify strlen.
  202. return this->operator<<(StringRef(Str));
  203. }
  204. raw_ostream &operator<<(const std::string &Str) {
  205. // Avoid the fast path, it would only increase code size for a marginal win.
  206. return write(Str.data(), Str.length());
  207. }
  208. #if __cplusplus > 201402L
  209. raw_ostream &operator<<(const std::string_view &Str) {
  210. return write(Str.data(), Str.length());
  211. }
  212. #endif
  213. raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
  214. return write(Str.data(), Str.size());
  215. }
  216. raw_ostream &operator<<(unsigned long N);
  217. raw_ostream &operator<<(long N);
  218. raw_ostream &operator<<(unsigned long long N);
  219. raw_ostream &operator<<(long long N);
  220. raw_ostream &operator<<(const void *P);
  221. raw_ostream &operator<<(unsigned int N) {
  222. return this->operator<<(static_cast<unsigned long>(N));
  223. }
  224. raw_ostream &operator<<(int N) {
  225. return this->operator<<(static_cast<long>(N));
  226. }
  227. raw_ostream &operator<<(double N);
  228. /// Output \p N in hexadecimal, without any prefix or padding.
  229. raw_ostream &write_hex(unsigned long long N);
  230. // Change the foreground color of text.
  231. raw_ostream &operator<<(Colors C);
  232. /// Output a formatted UUID with dash separators.
  233. using uuid_t = uint8_t[16];
  234. raw_ostream &write_uuid(const uuid_t UUID);
  235. /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
  236. /// satisfy llvm::isPrint into an escape sequence.
  237. raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
  238. raw_ostream &write(unsigned char C);
  239. raw_ostream &write(const char *Ptr, size_t Size);
  240. // Formatted output, see the format() function in Support/Format.h.
  241. raw_ostream &operator<<(const format_object_base &Fmt);
  242. // Formatted output, see the leftJustify() function in Support/Format.h.
  243. raw_ostream &operator<<(const FormattedString &);
  244. // Formatted output, see the formatHex() function in Support/Format.h.
  245. raw_ostream &operator<<(const FormattedNumber &);
  246. // Formatted output, see the formatv() function in Support/FormatVariadic.h.
  247. raw_ostream &operator<<(const formatv_object_base &);
  248. // Formatted output, see the format_bytes() function in Support/Format.h.
  249. raw_ostream &operator<<(const FormattedBytes &);
  250. /// indent - Insert 'NumSpaces' spaces.
  251. raw_ostream &indent(unsigned NumSpaces);
  252. /// write_zeros - Insert 'NumZeros' nulls.
  253. raw_ostream &write_zeros(unsigned NumZeros);
  254. /// Changes the foreground color of text that will be output from this point
  255. /// forward.
  256. /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
  257. /// change only the bold attribute, and keep colors untouched
  258. /// @param Bold bold/brighter text, default false
  259. /// @param BG if true change the background, default: change foreground
  260. /// @returns itself so it can be used within << invocations
  261. virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false,
  262. bool BG = false);
  263. /// Resets the colors to terminal defaults. Call this when you are done
  264. /// outputting colored text, or before program exit.
  265. virtual raw_ostream &resetColor();
  266. /// Reverses the foreground and background colors.
  267. virtual raw_ostream &reverseColor();
  268. /// This function determines if this stream is connected to a "tty" or
  269. /// "console" window. That is, the output would be displayed to the user
  270. /// rather than being put on a pipe or stored in a file.
  271. virtual bool is_displayed() const { return false; }
  272. /// This function determines if this stream is displayed and supports colors.
  273. /// The result is unaffected by calls to enable_color().
  274. virtual bool has_colors() const { return is_displayed(); }
  275. // Enable or disable colors. Once enable_colors(false) is called,
  276. // changeColor() has no effect until enable_colors(true) is called.
  277. virtual void enable_colors(bool enable) { ColorEnabled = enable; }
  278. bool colors_enabled() const { return ColorEnabled; }
  279. /// Tie this stream to the specified stream. Replaces any existing tied-to
  280. /// stream. Specifying a nullptr unties the stream.
  281. void tie(raw_ostream *TieTo) { TiedStream = TieTo; }
  282. //===--------------------------------------------------------------------===//
  283. // Subclass Interface
  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. /// Return the current position within the stream, not counting the bytes
  301. /// currently in the buffer.
  302. virtual uint64_t current_pos() const = 0;
  303. protected:
  304. /// Use the provided buffer as the raw_ostream buffer. This is intended for
  305. /// use only by subclasses which can arrange for the output to go directly
  306. /// into the desired output buffer, instead of being copied on each flush.
  307. void SetBuffer(char *BufferStart, size_t Size) {
  308. SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
  309. }
  310. /// Return an efficient buffer size for the underlying output mechanism.
  311. virtual size_t preferred_buffer_size() const;
  312. /// Return the beginning of the current stream buffer, or 0 if the stream is
  313. /// unbuffered.
  314. const char *getBufferStart() const { return OutBufStart; }
  315. //===--------------------------------------------------------------------===//
  316. // Private Interface
  317. //===--------------------------------------------------------------------===//
  318. private:
  319. /// Install the given buffer and mode.
  320. void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
  321. /// Flush the current buffer, which is known to be non-empty. This outputs the
  322. /// currently buffered data and resets the buffer to empty.
  323. void flush_nonempty();
  324. /// Copy data into the buffer. Size must not be greater than the number of
  325. /// unused bytes in the buffer.
  326. void copy_to_buffer(const char *Ptr, size_t Size);
  327. /// Compute whether colors should be used and do the necessary work such as
  328. /// flushing. The result is affected by calls to enable_color().
  329. bool prepare_colors();
  330. /// Flush the tied-to stream (if present) and then write the required data.
  331. void flush_tied_then_write(const char *Ptr, size_t Size);
  332. virtual void anchor();
  333. };
  334. /// Call the appropriate insertion operator, given an rvalue reference to a
  335. /// raw_ostream object and return a stream of the same type as the argument.
  336. template <typename OStream, typename T>
  337. std::enable_if_t<!std::is_reference<OStream>::value &&
  338. std::is_base_of<raw_ostream, OStream>::value,
  339. OStream &&>
  340. operator<<(OStream &&OS, const T &Value) {
  341. OS << Value;
  342. return std::move(OS);
  343. }
  344. /// An abstract base class for streams implementations that also support a
  345. /// pwrite operation. This is useful for code that can mostly stream out data,
  346. /// but needs to patch in a header that needs to know the output size.
  347. class raw_pwrite_stream : public raw_ostream {
  348. virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
  349. void anchor() override;
  350. public:
  351. explicit raw_pwrite_stream(bool Unbuffered = false,
  352. OStreamKind K = OStreamKind::OK_OStream)
  353. : raw_ostream(Unbuffered, K) {}
  354. void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
  355. #ifndef NDEBUG
  356. uint64_t Pos = tell();
  357. // /dev/null always reports a pos of 0, so we cannot perform this check
  358. // in that case.
  359. if (Pos)
  360. assert(Size + Offset <= Pos && "We don't support extending the stream");
  361. #endif
  362. pwrite_impl(Ptr, Size, Offset);
  363. }
  364. };
  365. //===----------------------------------------------------------------------===//
  366. // File Output Streams
  367. //===----------------------------------------------------------------------===//
  368. /// A raw_ostream that writes to a file descriptor.
  369. ///
  370. class raw_fd_ostream : public raw_pwrite_stream {
  371. int FD;
  372. bool ShouldClose;
  373. bool SupportsSeeking = false;
  374. bool IsRegularFile = false;
  375. mutable Optional<bool> HasColors;
  376. #ifdef _WIN32
  377. /// True if this fd refers to a Windows console device. Mintty and other
  378. /// terminal emulators are TTYs, but they are not consoles.
  379. bool IsWindowsConsole = false;
  380. #endif
  381. std::error_code EC;
  382. uint64_t pos = 0;
  383. /// See raw_ostream::write_impl.
  384. void write_impl(const char *Ptr, size_t Size) override;
  385. void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
  386. /// Return the current position within the stream, not counting the bytes
  387. /// currently in the buffer.
  388. uint64_t current_pos() const override { return pos; }
  389. /// Determine an efficient buffer size.
  390. size_t preferred_buffer_size() const override;
  391. void anchor() override;
  392. protected:
  393. /// Set the flag indicating that an output error has been encountered.
  394. void error_detected(std::error_code EC) { this->EC = EC; }
  395. /// Return the file descriptor.
  396. int get_fd() const { return FD; }
  397. // Update the file position by increasing \p Delta.
  398. void inc_pos(uint64_t Delta) { pos += Delta; }
  399. public:
  400. /// Open the specified file for writing. If an error occurs, information
  401. /// about the error is put into EC, and the stream should be immediately
  402. /// destroyed;
  403. /// \p Flags allows optional flags to control how the file will be opened.
  404. ///
  405. /// As a special case, if Filename is "-", then the stream will use
  406. /// STDOUT_FILENO instead of opening a file. This will not close the stdout
  407. /// descriptor.
  408. raw_fd_ostream(StringRef Filename, std::error_code &EC);
  409. raw_fd_ostream(StringRef Filename, std::error_code &EC,
  410. sys::fs::CreationDisposition Disp);
  411. raw_fd_ostream(StringRef Filename, std::error_code &EC,
  412. sys::fs::FileAccess Access);
  413. raw_fd_ostream(StringRef Filename, std::error_code &EC,
  414. sys::fs::OpenFlags Flags);
  415. raw_fd_ostream(StringRef Filename, std::error_code &EC,
  416. sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
  417. sys::fs::OpenFlags Flags);
  418. /// FD is the file descriptor that this writes to. If ShouldClose is true,
  419. /// this closes the file when the stream is destroyed. If FD is for stdout or
  420. /// stderr, it will not be closed.
  421. raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
  422. OStreamKind K = OStreamKind::OK_OStream);
  423. ~raw_fd_ostream() override;
  424. /// Manually flush the stream and close the file. Note that this does not call
  425. /// fsync.
  426. void close();
  427. bool supportsSeeking() const { return SupportsSeeking; }
  428. bool isRegularFile() const { return IsRegularFile; }
  429. /// Flushes the stream and repositions the underlying file descriptor position
  430. /// to the offset specified from the beginning of the file.
  431. uint64_t seek(uint64_t off);
  432. bool is_displayed() const override;
  433. bool has_colors() const override;
  434. std::error_code error() const { return EC; }
  435. /// Return the value of the flag in this raw_fd_ostream indicating whether an
  436. /// output error has been encountered.
  437. /// This doesn't implicitly flush any pending output. Also, it doesn't
  438. /// guarantee to detect all errors unless the stream has been closed.
  439. bool has_error() const { return bool(EC); }
  440. /// Set the flag read by has_error() to false. If the error flag is set at the
  441. /// time when this raw_ostream's destructor is called, report_fatal_error is
  442. /// called to report the error. Use clear_error() after handling the error to
  443. /// avoid this behavior.
  444. ///
  445. /// "Errors should never pass silently.
  446. /// Unless explicitly silenced."
  447. /// - from The Zen of Python, by Tim Peters
  448. ///
  449. void clear_error() { EC = std::error_code(); }
  450. /// Locks the underlying file.
  451. ///
  452. /// @returns RAII object that releases the lock upon leaving the scope, if the
  453. /// locking was successful. Otherwise returns corresponding
  454. /// error code.
  455. ///
  456. /// The function blocks the current thread until the lock become available or
  457. /// error occurs.
  458. ///
  459. /// Possible use of this function may be as follows:
  460. ///
  461. /// @code{.cpp}
  462. /// if (auto L = stream.lock()) {
  463. /// // ... do action that require file to be locked.
  464. /// } else {
  465. /// handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) {
  466. /// // ... handle lock error.
  467. /// });
  468. /// }
  469. /// @endcode
  470. LLVM_NODISCARD Expected<sys::fs::FileLocker> lock();
  471. /// Tries to lock the underlying file within the specified period.
  472. ///
  473. /// @returns RAII object that releases the lock upon leaving the scope, if the
  474. /// locking was successful. Otherwise returns corresponding
  475. /// error code.
  476. ///
  477. /// It is used as @ref lock.
  478. LLVM_NODISCARD
  479. Expected<sys::fs::FileLocker> tryLockFor(Duration const& Timeout);
  480. };
  481. /// This returns a reference to a raw_fd_ostream for standard output. Use it
  482. /// like: outs() << "foo" << "bar";
  483. raw_fd_ostream &outs();
  484. /// This returns a reference to a raw_ostream for standard error.
  485. /// Use it like: errs() << "foo" << "bar";
  486. /// By default, the stream is tied to stdout to ensure stdout is flushed before
  487. /// stderr is written, to ensure the error messages are written in their
  488. /// expected place.
  489. raw_fd_ostream &errs();
  490. /// This returns a reference to a raw_ostream which simply discards output.
  491. raw_ostream &nulls();
  492. //===----------------------------------------------------------------------===//
  493. // File Streams
  494. //===----------------------------------------------------------------------===//
  495. /// A raw_ostream of a file for reading/writing/seeking.
  496. ///
  497. class raw_fd_stream : public raw_fd_ostream {
  498. public:
  499. /// Open the specified file for reading/writing/seeking. If an error occurs,
  500. /// information about the error is put into EC, and the stream should be
  501. /// immediately destroyed.
  502. raw_fd_stream(StringRef Filename, std::error_code &EC);
  503. /// This reads the \p Size bytes into a buffer pointed by \p Ptr.
  504. ///
  505. /// \param Ptr The start of the buffer to hold data to be read.
  506. ///
  507. /// \param Size The number of bytes to be read.
  508. ///
  509. /// On success, the number of bytes read is returned, and the file position is
  510. /// advanced by this number. On error, -1 is returned, use error() to get the
  511. /// error code.
  512. ssize_t read(char *Ptr, size_t Size);
  513. /// Check if \p OS is a pointer of type raw_fd_stream*.
  514. static bool classof(const raw_ostream *OS);
  515. };
  516. //===----------------------------------------------------------------------===//
  517. // Output Stream Adaptors
  518. //===----------------------------------------------------------------------===//
  519. /// A raw_ostream that writes to an std::string. This is a simple adaptor
  520. /// class. This class does not encounter output errors.
  521. /// raw_string_ostream operates without a buffer, delegating all memory
  522. /// management to the std::string. Thus the std::string is always up-to-date,
  523. /// may be used directly and there is no need to call flush().
  524. class raw_string_ostream : public raw_ostream {
  525. std::string &OS;
  526. /// See raw_ostream::write_impl.
  527. void write_impl(const char *Ptr, size_t Size) override;
  528. /// Return the current position within the stream, not counting the bytes
  529. /// currently in the buffer.
  530. uint64_t current_pos() const override { return OS.size(); }
  531. public:
  532. explicit raw_string_ostream(std::string &O) : OS(O) {
  533. SetUnbuffered();
  534. }
  535. /// Returns the string's reference. In most cases it is better to simply use
  536. /// the underlying std::string directly.
  537. /// TODO: Consider removing this API.
  538. std::string &str() { return OS; }
  539. void reserveExtraSpace(uint64_t ExtraSize) override {
  540. OS.reserve(tell() + ExtraSize);
  541. }
  542. };
  543. /// A raw_ostream that writes to an SmallVector or SmallString. This is a
  544. /// simple adaptor class. This class does not encounter output errors.
  545. /// raw_svector_ostream operates without a buffer, delegating all memory
  546. /// management to the SmallString. Thus the SmallString is always up-to-date,
  547. /// may be used directly and there is no need to call flush().
  548. class raw_svector_ostream : public raw_pwrite_stream {
  549. SmallVectorImpl<char> &OS;
  550. /// See raw_ostream::write_impl.
  551. void write_impl(const char *Ptr, size_t Size) override;
  552. void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
  553. /// Return the current position within the stream.
  554. uint64_t current_pos() const override;
  555. public:
  556. /// Construct a new raw_svector_ostream.
  557. ///
  558. /// \param O The vector to write to; this should generally have at least 128
  559. /// bytes free to avoid any extraneous memory overhead.
  560. explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
  561. SetUnbuffered();
  562. }
  563. ~raw_svector_ostream() override = default;
  564. void flush() = delete;
  565. /// Return a StringRef for the vector contents.
  566. StringRef str() const { return StringRef(OS.data(), OS.size()); }
  567. void reserveExtraSpace(uint64_t ExtraSize) override {
  568. OS.reserve(tell() + ExtraSize);
  569. }
  570. };
  571. /// A raw_ostream that discards all output.
  572. class raw_null_ostream : public raw_pwrite_stream {
  573. /// See raw_ostream::write_impl.
  574. void write_impl(const char *Ptr, size_t size) override;
  575. void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
  576. /// Return the current position within the stream, not counting the bytes
  577. /// currently in the buffer.
  578. uint64_t current_pos() const override;
  579. public:
  580. explicit raw_null_ostream() = default;
  581. ~raw_null_ostream() override;
  582. };
  583. class buffer_ostream : public raw_svector_ostream {
  584. raw_ostream &OS;
  585. SmallVector<char, 0> Buffer;
  586. virtual void anchor() override;
  587. public:
  588. buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
  589. ~buffer_ostream() override { OS << str(); }
  590. };
  591. class buffer_unique_ostream : public raw_svector_ostream {
  592. std::unique_ptr<raw_ostream> OS;
  593. SmallVector<char, 0> Buffer;
  594. virtual void anchor() override;
  595. public:
  596. buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)
  597. : raw_svector_ostream(Buffer), OS(std::move(OS)) {
  598. // Turn off buffering on OS, which we now own, to avoid allocating a buffer
  599. // when the destructor writes only to be immediately flushed again.
  600. this->OS->SetUnbuffered();
  601. }
  602. ~buffer_unique_ostream() override { *OS << str(); }
  603. };
  604. class Error;
  605. /// This helper creates an output stream and then passes it to \p Write.
  606. /// The stream created is based on the specified \p OutputFileName:
  607. /// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream
  608. /// for other names. For raw_fd_ostream instances, the stream writes to
  609. /// a temporary file. The final output file is atomically replaced with the
  610. /// temporary file after the \p Write function is finished.
  611. Error writeToOutput(StringRef OutputFileName,
  612. std::function<Error(raw_ostream &)> Write);
  613. } // end namespace llvm
  614. #endif // LLVM_SUPPORT_RAW_OSTREAM_H
  615. #ifdef __GNUC__
  616. #pragma GCC diagnostic pop
  617. #endif