raw_ostream.h 27 KB

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