2 //===----------------------------------------------------------------------===//
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
15 // [print.fun], print functions
16 template<class... Args>
17 void print(format_string<Args...> fmt, Args&&... args);
18 void println(); // Since C++26
19 template<class... Args>
20 void print(FILE* stream, format_string<Args...> fmt, Args&&... args);
21 void println(FILE* stream); // Since C++26
23 template<class... Args>
24 void println(format_string<Args...> fmt, Args&&... args);
25 template<class... Args>
26 void println(FILE* stream, format_string<Args...> fmt, Args&&... args);
28 void vprint_unicode(string_view fmt, format_args args);
29 void vprint_unicode(FILE* stream, string_view fmt, format_args args);
31 void vprint_nonunicode(string_view fmt, format_args args);
32 void vprint_nonunicode(FILE* stream, string_view fmt, format_args args);
37 #include <__concepts/same_as.h>
39 #include <__system_error/throw_system_error.h>
40 #include <__utility/forward.h>
45 #include <string_view>
48 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
49 # pragma GCC system_header
52 _LIBCPP_BEGIN_NAMESPACE_STD
54 #ifdef _LIBCPP_WIN32API
55 _LIBCPP_EXPORTED_FROM_ABI bool __is_windows_terminal(FILE* __stream);
57 # if _LIBCPP_HAS_WIDE_CHARACTERS
58 // A wrapper for WriteConsoleW which is used to write to the Windows
59 // console. This function is in the dylib to avoid pulling in windows.h
60 // in the library headers. The function itself uses some private parts
63 // The function does not depend on the language standard used. Guarding
64 // it with C++23 would fail since the dylib is currently built using C++20.
66 // Note the function is only implemented on the Windows platform.
67 _LIBCPP_EXPORTED_FROM_ABI void __write_to_windows_console(FILE* __stream, wstring_view __view);
68 # endif // _LIBCPP_HAS_WIDE_CHARACTERS
69 #elif __has_include(<unistd.h>)
70 _LIBCPP_EXPORTED_FROM_ABI bool __is_posix_terminal(FILE* __stream);
71 #endif // _LIBCPP_WIN32API
73 #if _LIBCPP_STD_VER >= 23
75 # if _LIBCPP_HAS_UNICODE
76 // This is the code to transcode UTF-8 to UTF-16. This is used on
77 // Windows for the native Unicode API. The code is modeled to make it
78 // easier to extend to
80 // P2728R0 Unicode in the Library, Part 1: UTF Transcoding
82 // This paper is still under heavy development so it makes no sense yet
83 // to strictly follow the paper.
86 // The names of these concepts are modelled after P2728R0, but the
87 // implementation is not. char16_t may contain 32-bits so depending on the
88 // number of bits is an issue.
89 # ifdef _LIBCPP_SHORT_WCHAR
91 concept __utf16_code_unit =
92 same_as<_Tp, char16_t>
93 # if _LIBCPP_HAS_WIDE_CHARACTERS
94 || same_as<_Tp, wchar_t>
98 concept __utf32_code_unit = same_as<_Tp, char32_t>;
99 # else // _LIBCPP_SHORT_WCHAR
101 concept __utf16_code_unit = same_as<_Tp, char16_t>;
103 concept __utf32_code_unit =
104 same_as<_Tp, char32_t>
105 # if _LIBCPP_HAS_WIDE_CHARACTERS
106 || same_as<_Tp, wchar_t>
109 # endif // _LIBCPP_SHORT_WCHAR
111 // Pass by reference since an output_iterator may not be copyable.
112 template <class _OutIt>
113 _LIBCPP_HIDE_FROM_ABI constexpr void __encode(_OutIt&, char32_t) = delete;
115 template <class _OutIt>
116 requires __utf16_code_unit<iter_value_t<_OutIt>>
117 _LIBCPP_HIDE_FROM_ABI constexpr void __encode(_OutIt& __out_it, char32_t __value) {
118 // [print.fun]/7 : "if `out` contains invalid code units, the behavior is undefined and implementations are encouraged
120 _LIBCPP_ASSERT_UNCATEGORIZED(__is_scalar_value(__value), "an invalid unicode scalar value results in invalid UTF-16");
122 if (__value < 0x10000) {
123 *__out_it++ = __value;
128 *__out_it++ = 0xd800 + (__value >> 10);
129 *__out_it++ = 0xdc00 + (__value & 0x3FF);
132 template <class _OutIt>
133 requires __utf32_code_unit<iter_value_t<_OutIt>>
134 _LIBCPP_HIDE_FROM_ABI constexpr void __encode(_OutIt& __out_it, char32_t __value) {
135 // [print.fun]/7 : "if `out` contains invalid code units, the behavior is undefined and implementations are encouraged
137 _LIBCPP_ASSERT_UNCATEGORIZED(__is_scalar_value(__value), "an invalid unicode scalar value results in invalid UTF-32");
138 *__out_it++ = __value;
141 template <class _OutIt, input_iterator _InIt>
142 requires output_iterator<_OutIt, const iter_value_t<_OutIt>&> && (!same_as<iter_value_t<_OutIt>, iter_value_t<_InIt>>)
143 _LIBCPP_HIDE_FROM_ABI constexpr _OutIt __transcode(_InIt __first, _InIt __last, _OutIt __out_it) {
144 // The __code_point_view has a basic_string_view interface.
145 // When transcoding becomes part of the standard we probably want to
146 // look at smarter algorithms.
147 // For example, when processing a code point that is encoded in
148 // 1 to 3 code units in UTF-8, the result will always be encoded
149 // in 1 code unit in UTF-16 (code points that require 4 code
150 // units in UTF-8 will require 2 code units in UTF-16).
152 // Note if P2728 is accepted types like int may become valid. In that case
153 // the __code_point_view should use a span. Libc++ will remove support for
156 // TODO PRINT Validate with clang-tidy
157 // NOLINTNEXTLINE(bugprone-dangling-handle)
158 basic_string_view<iter_value_t<_InIt>> __data{__first, __last};
159 __code_point_view<iter_value_t<_InIt>> __view{__data.begin(), __data.end()};
160 while (!__view.__at_end())
161 __unicode::__encode(__out_it, __view.__consume().__code_point);
165 } // namespace __unicode
167 # endif // _LIBCPP_HAS_UNICODE
172 // Effects: If the ordinary literal encoding ([lex.charset]) is UTF-8, equivalent to:
173 // vprint_unicode(stream, fmt.str, make_format_args(args...));
174 // Otherwise, equivalent to:
175 // vprint_nonunicode(stream, fmt.str, make_format_args(args...));
177 // Based on the compiler and its compilation flags this value is or is
178 // not true. As mentioned in P2093R14 this only affects Windows. The
179 // test below could also be done for
180 // - GCC using __GNUC_EXECUTION_CHARSET_NAME
181 // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
182 // - Clang using __clang_literal_encoding__
183 // https://clang.llvm.org/docs/LanguageExtensions.html#builtin-macros
184 // (note at the time of writing Clang is hard-coded to UTF-8.)
187 # if !_LIBCPP_HAS_UNICODE
188 inline constexpr bool __use_unicode_execution_charset = false;
189 # elif defined(_MSVC_EXECUTION_CHARACTER_SET)
190 // This is the same test MSVC STL uses in their implementation of <print>
191 // See: https://learn.microsoft.com/en-us/windows/win32/intl/code-page-identifiers
192 inline constexpr bool __use_unicode_execution_charset = _MSVC_EXECUTION_CHARACTER_SET == 65001;
194 inline constexpr bool __use_unicode_execution_charset = true;
197 _LIBCPP_HIDE_FROM_ABI inline bool __is_terminal([[maybe_unused]] FILE* __stream) {
198 // The macro _LIBCPP_TESTING_PRINT_IS_TERMINAL is used to change
199 // the behavior in the test. This is not part of the public API.
200 # ifdef _LIBCPP_TESTING_PRINT_IS_TERMINAL
201 return _LIBCPP_TESTING_PRINT_IS_TERMINAL(__stream);
202 # elif _LIBCPP_AVAILABILITY_HAS_PRINT == 0 || !_LIBCPP_HAS_TERMINAL
204 # elif defined(_LIBCPP_WIN32API)
205 return std::__is_windows_terminal(__stream);
206 # elif __has_include(<unistd.h>)
207 return std::__is_posix_terminal(__stream);
209 # error "Provide a way to determine whether a FILE* is a terminal"
213 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
214 _LIBCPP_HIDE_FROM_ABI inline void
215 __vprint_nonunicode(FILE* __stream, string_view __fmt, format_args __args, bool __write_nl) {
216 _LIBCPP_ASSERT_NON_NULL(__stream, "__stream must be a valid pointer to an output C stream");
217 string __str = std::vformat(__fmt, __args);
219 __str.push_back('\n');
221 size_t __size = fwrite(__str.data(), 1, __str.size(), __stream);
222 if (__size < __str.size()) {
223 if (std::feof(__stream))
224 std::__throw_system_error(EIO, "EOF while writing the formatted output");
225 std::__throw_system_error(std::ferror(__stream), "failed to write formatted output");
229 # if _LIBCPP_HAS_UNICODE
231 // Note these helper functions are mainly used to aid testing.
232 // On POSIX systems and Windows the output is no longer considered a
233 // terminal when the output is redirected. Typically during testing the
234 // output is redirected to be able to capture it. This makes it hard to
235 // test this code path.
236 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
237 _LIBCPP_HIDE_FROM_ABI inline void
238 __vprint_unicode_posix(FILE* __stream, string_view __fmt, format_args __args, bool __write_nl, bool __is_terminal) {
239 // TODO PRINT Should flush errors throw too?
241 std::fflush(__stream);
243 __print::__vprint_nonunicode(__stream, __fmt, __args, __write_nl);
246 # if _LIBCPP_HAS_WIDE_CHARACTERS
247 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
248 _LIBCPP_HIDE_FROM_ABI inline void
249 __vprint_unicode_windows(FILE* __stream, string_view __fmt, format_args __args, bool __write_nl, bool __is_terminal) {
251 return __print::__vprint_nonunicode(__stream, __fmt, __args, __write_nl);
253 // TODO PRINT Should flush errors throw too?
254 std::fflush(__stream);
256 string __str = std::vformat(__fmt, __args);
257 // UTF-16 uses the same number or less code units than UTF-8.
258 // However the size of the code unit is 16 bits instead of 8 bits.
260 // The buffer uses the worst-case estimate and should never resize.
261 // However when the string is large this could lead to OOM. Using a
262 // smaller size might work, but since the buffer uses a grow factor
263 // the final size might be larger when the estimate is wrong.
265 // TODO PRINT profile and improve the speed of this code.
266 __format::__retarget_buffer<wchar_t> __buffer{__str.size()};
267 __unicode::__transcode(__str.begin(), __str.end(), __buffer.__make_output_iterator());
269 __buffer.push_back(L'\n');
271 [[maybe_unused]] wstring_view __view = __buffer.__view();
273 // The macro _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION is used to change
274 // the behavior in the test. This is not part of the public API.
275 # ifdef _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION
276 _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION(__stream, __view);
277 # elif defined(_LIBCPP_WIN32API)
278 std::__write_to_windows_console(__stream, __view);
280 std::__throw_runtime_error("No defintion of _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION and "
281 "__write_to_windows_console is not available.");
284 # endif // _LIBCPP_HAS_WIDE_CHARACTERS
286 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
287 _LIBCPP_HIDE_FROM_ABI inline void
288 __vprint_unicode([[maybe_unused]] FILE* __stream,
289 [[maybe_unused]] string_view __fmt,
290 [[maybe_unused]] format_args __args,
291 [[maybe_unused]] bool __write_nl) {
292 _LIBCPP_ASSERT_NON_NULL(__stream, "__stream must be a valid pointer to an output C stream");
295 // 7 - Effects: If stream refers to a terminal capable of displaying
296 // Unicode, writes out to the terminal using the native Unicode
297 // API; if out contains invalid code units, the behavior is
298 // undefined and implementations are encouraged to diagnose it.
299 // Otherwise writes out to stream unchanged. If the native
300 // Unicode API is used, the function flushes stream before
302 // 8 - Throws: Any exception thrown by the call to vformat
303 // ([format.err.report]). system_error if writing to the terminal
304 // or stream fails. May throw bad_alloc.
305 // 9 - Recommended practice: If invoking the native Unicode API
306 // requires transcoding, implementations should substitute
307 // invalid code units with U+FFFD replacement character per the
308 // Unicode Standard, Chapter 3.9 U+FFFD Substitution in
311 // On non-Windows platforms the Unicode API is the normal file I/O API
312 // so there the call can be forwarded to the non_unicode API. On
313 // Windows there is a different API. This API requires transcoding.
315 # ifndef _LIBCPP_WIN32API
316 __print::__vprint_unicode_posix(__stream, __fmt, __args, __write_nl, __print::__is_terminal(__stream));
317 # elif _LIBCPP_HAS_WIDE_CHARACTERS
318 __print::__vprint_unicode_windows(__stream, __fmt, __args, __write_nl, __print::__is_terminal(__stream));
320 # error "Windows builds with wchar_t disabled are not supported."
324 # endif // _LIBCPP_HAS_UNICODE
326 } // namespace __print
328 template <class... _Args>
329 _LIBCPP_HIDE_FROM_ABI void print(FILE* __stream, format_string<_Args...> __fmt, _Args&&... __args) {
330 # if _LIBCPP_HAS_UNICODE
331 if constexpr (__print::__use_unicode_execution_charset)
332 __print::__vprint_unicode(__stream, __fmt.get(), std::make_format_args(__args...), false);
334 __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), false);
335 # else // _LIBCPP_HAS_UNICODE
336 __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), false);
337 # endif // _LIBCPP_HAS_UNICODE
340 template <class... _Args>
341 _LIBCPP_HIDE_FROM_ABI void print(format_string<_Args...> __fmt, _Args&&... __args) {
342 std::print(stdout, __fmt, std::forward<_Args>(__args)...);
345 template <class... _Args>
346 _LIBCPP_HIDE_FROM_ABI void println(FILE* __stream, format_string<_Args...> __fmt, _Args&&... __args) {
347 # if _LIBCPP_HAS_UNICODE
348 // Note the wording in the Standard is inefficient. The output of
349 // std::format is a std::string which is then copied. This solution
350 // just appends a newline at the end of the output.
351 if constexpr (__print::__use_unicode_execution_charset)
352 __print::__vprint_unicode(__stream, __fmt.get(), std::make_format_args(__args...), true);
354 __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), true);
355 # else // _LIBCPP_HAS_UNICODE
356 __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), true);
357 # endif // _LIBCPP_HAS_UNICODE
360 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
361 _LIBCPP_HIDE_FROM_ABI inline void println(FILE* __stream) {
362 std::print(__stream, "\n");
365 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
366 _LIBCPP_HIDE_FROM_ABI inline void println() {
370 template <class... _Args>
371 _LIBCPP_HIDE_FROM_ABI void println(format_string<_Args...> __fmt, _Args&&... __args) {
372 std::println(stdout, __fmt, std::forward<_Args>(__args)...);
375 # if _LIBCPP_HAS_UNICODE
376 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
377 _LIBCPP_HIDE_FROM_ABI inline void vprint_unicode(FILE* __stream, string_view __fmt, format_args __args) {
378 __print::__vprint_unicode(__stream, __fmt, __args, false);
381 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
382 _LIBCPP_HIDE_FROM_ABI inline void vprint_unicode(string_view __fmt, format_args __args) {
383 std::vprint_unicode(stdout, __fmt, __args);
386 # endif // _LIBCPP_HAS_UNICODE
388 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
389 _LIBCPP_HIDE_FROM_ABI inline void vprint_nonunicode(FILE* __stream, string_view __fmt, format_args __args) {
390 __print::__vprint_nonunicode(__stream, __fmt, __args, false);
393 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
394 _LIBCPP_HIDE_FROM_ABI inline void vprint_nonunicode(string_view __fmt, format_args __args) {
395 std::vprint_nonunicode(stdout, __fmt, __args);
398 #endif // _LIBCPP_STD_VER >= 23
400 _LIBCPP_END_NAMESPACE_STD
402 #endif // _LIBCPP_PRINT