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