Back to home page

EIC code displayed by LXR

 
 

    


Warning, /include/c++/v1/__cxx03/print is written in an unsupported language. File is not indexed.

0001 // -*- C++ -*-
0002 //===----------------------------------------------------------------------===//
0003 //
0004 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0005 // See https://llvm.org/LICENSE.txt for license information.
0006 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0007 //
0008 //===----------------------------------------------------------------------===//
0009 
0010 #ifndef _LIBCPP___CXX03_PRINT
0011 #define _LIBCPP___CXX03_PRINT
0012 
0013 /*
0014 namespace std {
0015   // [print.fun], print functions
0016   template<class... Args>
0017     void print(format_string<Args...> fmt, Args&&... args);
0018   void println();                                                          // Since C++26
0019   template<class... Args>
0020     void print(FILE* stream, format_string<Args...> fmt, Args&&... args);
0021   void println(FILE* stream);                                              // Since C++26
0022 
0023   template<class... Args>
0024     void println(format_string<Args...> fmt, Args&&... args);
0025   template<class... Args>
0026     void println(FILE* stream, format_string<Args...> fmt, Args&&... args);
0027 
0028   void vprint_unicode(string_view fmt, format_args args);
0029   void vprint_unicode(FILE* stream, string_view fmt, format_args args);
0030 
0031   void vprint_nonunicode(string_view fmt, format_args args);
0032   void vprint_nonunicode(FILE* stream, string_view fmt, format_args args);
0033 }
0034 */
0035 
0036 #include <__cxx03/__assert>
0037 #include <__cxx03/__concepts/same_as.h>
0038 #include <__cxx03/__config>
0039 #include <__cxx03/__system_error/system_error.h>
0040 #include <__cxx03/__utility/forward.h>
0041 #include <__cxx03/cerrno>
0042 #include <__cxx03/cstdio>
0043 #include <__cxx03/format>
0044 #include <__cxx03/string>
0045 #include <__cxx03/string_view>
0046 #include <__cxx03/version>
0047 
0048 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
0049 #  pragma GCC system_header
0050 #endif
0051 
0052 _LIBCPP_BEGIN_NAMESPACE_STD
0053 
0054 #ifdef _LIBCPP_WIN32API
0055 _LIBCPP_EXPORTED_FROM_ABI bool __is_windows_terminal(FILE* __stream);
0056 
0057 #  ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
0058 // A wrapper for WriteConsoleW which is used to write to the Windows
0059 // console. This function is in the dylib to avoid pulling in windows.h
0060 // in the library headers. The function itself uses some private parts
0061 // of the dylib too.
0062 //
0063 // The function does not depend on the language standard used. Guarding
0064 // it with C++23 would fail since the dylib is currently built using C++20.
0065 //
0066 // Note the function is only implemented on the Windows platform.
0067 _LIBCPP_EXPORTED_FROM_ABI void __write_to_windows_console(FILE* __stream, wstring_view __view);
0068 #  endif // _LIBCPP_HAS_NO_WIDE_CHARACTERS
0069 #elif __has_include(<unistd.h>)
0070 _LIBCPP_EXPORTED_FROM_ABI bool __is_posix_terminal(FILE* __stream);
0071 #endif // _LIBCPP_WIN32API
0072 
0073 #if _LIBCPP_STD_VER >= 23
0074 
0075 #  ifndef _LIBCPP_HAS_NO_UNICODE
0076 // This is the code to transcode UTF-8 to UTF-16. This is used on
0077 // Windows for the native Unicode API. The code is modeled to make it
0078 // easier to extend to
0079 //
0080 //  P2728R0 Unicode in the Library, Part 1: UTF Transcoding
0081 //
0082 // This paper is still under heavy development so it makes no sense yet
0083 // to strictly follow the paper.
0084 namespace __unicode {
0085 
0086 // The names of these concepts are modelled after P2728R0, but the
0087 // implementation is not. char16_t may contain 32-bits so depending on the
0088 // number of bits is an issue.
0089 #    ifdef _LIBCPP_SHORT_WCHAR
0090 template <class _Tp>
0091 concept __utf16_code_unit =
0092     same_as<_Tp, char16_t>
0093 #      ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
0094     || same_as<_Tp, wchar_t>
0095 #      endif
0096     ;
0097 template <class _Tp>
0098 concept __utf32_code_unit = same_as<_Tp, char32_t>;
0099 #    else // _LIBCPP_SHORT_WCHAR
0100 template <class _Tp>
0101 concept __utf16_code_unit = same_as<_Tp, char16_t>;
0102 template <class _Tp>
0103 concept __utf32_code_unit =
0104     same_as<_Tp, char32_t>
0105 #      ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
0106     || same_as<_Tp, wchar_t>
0107 #      endif
0108     ;
0109 #    endif // _LIBCPP_SHORT_WCHAR
0110 
0111 // Pass by reference since an output_iterator may not be copyable.
0112 template <class _OutIt>
0113 _LIBCPP_HIDE_FROM_ABI constexpr void __encode(_OutIt&, char32_t) = delete;
0114 
0115 template <class _OutIt>
0116   requires __utf16_code_unit<iter_value_t<_OutIt>>
0117 _LIBCPP_HIDE_FROM_ABI constexpr void __encode(_OutIt& __out_it, char32_t __value) {
0118   // [print.fun]/7 : "if `out` contains invalid code units, the behavior is undefined and implementations are encouraged
0119   // to diagnose it".
0120   _LIBCPP_ASSERT_UNCATEGORIZED(__is_scalar_value(__value), "an invalid unicode scalar value results in invalid UTF-16");
0121 
0122   if (__value < 0x10000) {
0123     *__out_it++ = __value;
0124     return;
0125   }
0126 
0127   __value -= 0x10000;
0128   *__out_it++ = 0xd800 + (__value >> 10);
0129   *__out_it++ = 0xdc00 + (__value & 0x3FF);
0130 }
0131 
0132 template <class _OutIt>
0133   requires __utf32_code_unit<iter_value_t<_OutIt>>
0134 _LIBCPP_HIDE_FROM_ABI constexpr void __encode(_OutIt& __out_it, char32_t __value) {
0135   // [print.fun]/7 : "if `out` contains invalid code units, the behavior is undefined and implementations are encouraged
0136   // to diagnose it".
0137   _LIBCPP_ASSERT_UNCATEGORIZED(__is_scalar_value(__value), "an invalid unicode scalar value results in invalid UTF-32");
0138   *__out_it++ = __value;
0139 }
0140 
0141 template <class _OutIt, input_iterator _InIt>
0142   requires output_iterator<_OutIt, const iter_value_t<_OutIt>&> && (!same_as<iter_value_t<_OutIt>, iter_value_t<_InIt>>)
0143 _LIBCPP_HIDE_FROM_ABI constexpr _OutIt __transcode(_InIt __first, _InIt __last, _OutIt __out_it) {
0144   // The __code_point_view has a basic_string_view interface.
0145   // When transcoding becomes part of the standard we probably want to
0146   // look at smarter algorithms.
0147   // For example, when processing a code point that is encoded in
0148   // 1 to 3 code units in UTF-8, the result will always be encoded
0149   // in 1 code unit in UTF-16 (code points that require 4 code
0150   // units in UTF-8 will require 2 code units in UTF-16).
0151   //
0152   // Note if P2728 is accepted types like int may become valid. In that case
0153   // the __code_point_view should use a span. Libc++ will remove support for
0154   // char_traits<int>.
0155 
0156   // TODO PRINT Validate with clang-tidy
0157   // NOLINTNEXTLINE(bugprone-dangling-handle)
0158   basic_string_view<iter_value_t<_InIt>> __data{__first, __last};
0159   __code_point_view<iter_value_t<_InIt>> __view{__data.begin(), __data.end()};
0160   while (!__view.__at_end())
0161     __unicode::__encode(__out_it, __view.__consume().__code_point);
0162   return __out_it;
0163 }
0164 
0165 } // namespace __unicode
0166 
0167 #  endif //  _LIBCPP_HAS_NO_UNICODE
0168 
0169 namespace __print {
0170 
0171 // [print.fun]/2
0172 //   Effects: If the ordinary literal encoding ([lex.charset]) is UTF-8, equivalent to:
0173 //     vprint_unicode(stream, fmt.str, make_format_args(args...));
0174 //   Otherwise, equivalent to:
0175 //     vprint_nonunicode(stream, fmt.str, make_format_args(args...));
0176 //
0177 // Based on the compiler and its compilation flags this value is or is
0178 // not true. As mentioned in P2093R14 this only affects Windows. The
0179 // test below could also be done for
0180 // - GCC using __GNUC_EXECUTION_CHARSET_NAME
0181 //   https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
0182 // - Clang using __clang_literal_encoding__
0183 //   https://clang.llvm.org/docs/LanguageExtensions.html#builtin-macros
0184 //   (note at the time of writing Clang is hard-coded to UTF-8.)
0185 //
0186 
0187 #  ifdef _LIBCPP_HAS_NO_UNICODE
0188 inline constexpr bool __use_unicode_execution_charset = false;
0189 #  elif defined(_MSVC_EXECUTION_CHARACTER_SET)
0190 // This is the same test MSVC STL uses in their implementation of <print>
0191 // See: https://learn.microsoft.com/en-us/windows/win32/intl/code-page-identifiers
0192 inline constexpr bool __use_unicode_execution_charset = _MSVC_EXECUTION_CHARACTER_SET == 65001;
0193 #  else
0194 inline constexpr bool __use_unicode_execution_charset = true;
0195 #  endif
0196 
0197 _LIBCPP_HIDE_FROM_ABI inline bool __is_terminal([[maybe_unused]] FILE* __stream) {
0198   // The macro _LIBCPP_TESTING_PRINT_IS_TERMINAL is used to change
0199   // the behavior in the test. This is not part of the public API.
0200 #  ifdef _LIBCPP_TESTING_PRINT_IS_TERMINAL
0201   return _LIBCPP_TESTING_PRINT_IS_TERMINAL(__stream);
0202 #  elif _LIBCPP_AVAILABILITY_HAS_PRINT == 0
0203   return false;
0204 #  elif defined(_LIBCPP_WIN32API)
0205   return std::__is_windows_terminal(__stream);
0206 #  elif __has_include(<unistd.h>)
0207   return std::__is_posix_terminal(__stream);
0208 #  else
0209 #    error "Provide a way to determine whether a FILE* is a terminal"
0210 #  endif
0211 }
0212 
0213 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0214 _LIBCPP_HIDE_FROM_ABI inline void
0215 __vprint_nonunicode(FILE* __stream, string_view __fmt, format_args __args, bool __write_nl) {
0216   _LIBCPP_ASSERT_NON_NULL(__stream, "__stream must be a valid pointer to an output C stream");
0217   string __str = std::vformat(__fmt, __args);
0218   if (__write_nl)
0219     __str.push_back('\n');
0220 
0221   size_t __size = fwrite(__str.data(), 1, __str.size(), __stream);
0222   if (__size < __str.size()) {
0223     if (std::feof(__stream))
0224       std::__throw_system_error(EIO, "EOF while writing the formatted output");
0225     std::__throw_system_error(std::ferror(__stream), "failed to write formatted output");
0226   }
0227 }
0228 
0229 #  ifndef _LIBCPP_HAS_NO_UNICODE
0230 
0231 // Note these helper functions are mainly used to aid testing.
0232 // On POSIX systems and Windows the output is no longer considered a
0233 // terminal when the output is redirected. Typically during testing the
0234 // output is redirected to be able to capture it. This makes it hard to
0235 // test this code path.
0236 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0237 _LIBCPP_HIDE_FROM_ABI inline void
0238 __vprint_unicode_posix(FILE* __stream, string_view __fmt, format_args __args, bool __write_nl, bool __is_terminal) {
0239   // TODO PRINT Should flush errors throw too?
0240   if (__is_terminal)
0241     std::fflush(__stream);
0242 
0243   __print::__vprint_nonunicode(__stream, __fmt, __args, __write_nl);
0244 }
0245 
0246 #    ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
0247 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0248 _LIBCPP_HIDE_FROM_ABI inline void
0249 __vprint_unicode_windows(FILE* __stream, string_view __fmt, format_args __args, bool __write_nl, bool __is_terminal) {
0250   if (!__is_terminal)
0251     return __print::__vprint_nonunicode(__stream, __fmt, __args, __write_nl);
0252 
0253   // TODO PRINT Should flush errors throw too?
0254   std::fflush(__stream);
0255 
0256   string __str = std::vformat(__fmt, __args);
0257   // UTF-16 uses the same number or less code units than UTF-8.
0258   // However the size of the code unit is 16 bits instead of 8 bits.
0259   //
0260   // The buffer uses the worst-case estimate and should never resize.
0261   // However when the string is large this could lead to OOM. Using a
0262   // smaller size might work, but since the buffer uses a grow factor
0263   // the final size might be larger when the estimate is wrong.
0264   //
0265   // TODO PRINT profile and improve the speed of this code.
0266   __format::__retarget_buffer<wchar_t> __buffer{__str.size()};
0267   __unicode::__transcode(__str.begin(), __str.end(), __buffer.__make_output_iterator());
0268   if (__write_nl)
0269     __buffer.push_back(L'\n');
0270 
0271   [[maybe_unused]] wstring_view __view = __buffer.__view();
0272 
0273   // The macro _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION is used to change
0274   // the behavior in the test. This is not part of the public API.
0275 #      ifdef _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION
0276   _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION(__stream, __view);
0277 #      elif defined(_LIBCPP_WIN32API)
0278   std::__write_to_windows_console(__stream, __view);
0279 #      else
0280   std::__throw_runtime_error("No defintion of _LIBCPP_TESTING_PRINT_WRITE_TO_WINDOWS_CONSOLE_FUNCTION and "
0281                              "__write_to_windows_console is not available.");
0282 #      endif
0283 }
0284 #    endif // _LIBCPP_HAS_NO_WIDE_CHARACTERS
0285 
0286 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0287 _LIBCPP_HIDE_FROM_ABI inline void
0288 __vprint_unicode([[maybe_unused]] FILE* __stream,
0289                  [[maybe_unused]] string_view __fmt,
0290                  [[maybe_unused]] format_args __args,
0291                  [[maybe_unused]] bool __write_nl) {
0292   _LIBCPP_ASSERT_NON_NULL(__stream, "__stream must be a valid pointer to an output C stream");
0293 
0294   // [print.fun]
0295   //   7 - Effects: If stream refers to a terminal capable of displaying
0296   //       Unicode, writes out to the terminal using the native Unicode
0297   //       API; if out contains invalid code units, the behavior is
0298   //       undefined and implementations are encouraged to diagnose it.
0299   //       Otherwise writes out to stream unchanged. If the native
0300   //       Unicode API is used, the function flushes stream before
0301   //       writing out.
0302   //   8 - Throws: Any exception thrown by the call to vformat
0303   //       ([format.err.report]). system_error if writing to the terminal
0304   //       or stream fails. May throw bad_alloc.
0305   //   9 - Recommended practice: If invoking the native Unicode API
0306   //       requires transcoding, implementations should substitute
0307   //       invalid code units with U+FFFD replacement character per the
0308   //       Unicode Standard, Chapter 3.9 U+FFFD Substitution in
0309   //       Conversion.
0310 
0311   // On non-Windows platforms the Unicode API is the normal file I/O API
0312   // so there the call can be forwarded to the non_unicode API. On
0313   // Windows there is a different API. This API requires transcoding.
0314 
0315 #    ifndef _LIBCPP_WIN32API
0316   __print::__vprint_unicode_posix(__stream, __fmt, __args, __write_nl, __print::__is_terminal(__stream));
0317 #    elif !defined(_LIBCPP_HAS_NO_WIDE_CHARACTERS)
0318   __print::__vprint_unicode_windows(__stream, __fmt, __args, __write_nl, __print::__is_terminal(__stream));
0319 #    else
0320 #      error "Windows builds with wchar_t disabled are not supported."
0321 #    endif
0322 }
0323 
0324 #  endif // _LIBCPP_HAS_NO_UNICODE
0325 
0326 } // namespace __print
0327 
0328 template <class... _Args>
0329 _LIBCPP_HIDE_FROM_ABI void print(FILE* __stream, format_string<_Args...> __fmt, _Args&&... __args) {
0330 #  ifndef _LIBCPP_HAS_NO_UNICODE
0331   if constexpr (__print::__use_unicode_execution_charset)
0332     __print::__vprint_unicode(__stream, __fmt.get(), std::make_format_args(__args...), false);
0333   else
0334     __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), false);
0335 #  else  // _LIBCPP_HAS_NO_UNICODE
0336   __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), false);
0337 #  endif // _LIBCPP_HAS_NO_UNICODE
0338 }
0339 
0340 template <class... _Args>
0341 _LIBCPP_HIDE_FROM_ABI void print(format_string<_Args...> __fmt, _Args&&... __args) {
0342   std::print(stdout, __fmt, std::forward<_Args>(__args)...);
0343 }
0344 
0345 template <class... _Args>
0346 _LIBCPP_HIDE_FROM_ABI void println(FILE* __stream, format_string<_Args...> __fmt, _Args&&... __args) {
0347 #  ifndef _LIBCPP_HAS_NO_UNICODE
0348   // Note the wording in the Standard is inefficient. The output of
0349   // std::format is a std::string which is then copied. This solution
0350   // just appends a newline at the end of the output.
0351   if constexpr (__print::__use_unicode_execution_charset)
0352     __print::__vprint_unicode(__stream, __fmt.get(), std::make_format_args(__args...), true);
0353   else
0354     __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), true);
0355 #  else  // _LIBCPP_HAS_NO_UNICODE
0356   __print::__vprint_nonunicode(__stream, __fmt.get(), std::make_format_args(__args...), true);
0357 #  endif // _LIBCPP_HAS_NO_UNICODE
0358 }
0359 
0360 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0361 _LIBCPP_HIDE_FROM_ABI inline void println(FILE* __stream) {
0362   std::print(__stream, "\n");
0363 }
0364 
0365 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0366 _LIBCPP_HIDE_FROM_ABI inline void println() {
0367   println(stdout);
0368 }
0369 
0370 template <class... _Args>
0371 _LIBCPP_HIDE_FROM_ABI void println(format_string<_Args...> __fmt, _Args&&... __args) {
0372   std::println(stdout, __fmt, std::forward<_Args>(__args)...);
0373 }
0374 
0375 #  ifndef _LIBCPP_HAS_NO_UNICODE
0376 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0377 _LIBCPP_HIDE_FROM_ABI inline void vprint_unicode(FILE* __stream, string_view __fmt, format_args __args) {
0378   __print::__vprint_unicode(__stream, __fmt, __args, false);
0379 }
0380 
0381 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0382 _LIBCPP_HIDE_FROM_ABI inline void vprint_unicode(string_view __fmt, format_args __args) {
0383   std::vprint_unicode(stdout, __fmt, __args);
0384 }
0385 
0386 #  endif // _LIBCPP_HAS_NO_UNICODE
0387 
0388 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0389 _LIBCPP_HIDE_FROM_ABI inline void vprint_nonunicode(FILE* __stream, string_view __fmt, format_args __args) {
0390   __print::__vprint_nonunicode(__stream, __fmt, __args, false);
0391 }
0392 
0393 template <class = void> // TODO PRINT template or availability markup fires too eagerly (http://llvm.org/PR61563).
0394 _LIBCPP_HIDE_FROM_ABI inline void vprint_nonunicode(string_view __fmt, format_args __args) {
0395   std::vprint_nonunicode(stdout, __fmt, __args);
0396 }
0397 
0398 #endif // _LIBCPP_STD_VER >= 23
0399 
0400 _LIBCPP_END_NAMESPACE_STD
0401 
0402 #endif // _LIBCPP___CXX03_PRINT