write_escaped.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  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
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP___FORMAT_WRITE_ESCAPED_H
  10. #define _LIBCPP___FORMAT_WRITE_ESCAPED_H
  11. #include <__algorithm/ranges_copy.h>
  12. #include <__algorithm/ranges_for_each.h>
  13. #include <__charconv/to_chars_integral.h>
  14. #include <__charconv/to_chars_result.h>
  15. #include <__chrono/statically_widen.h>
  16. #include <__format/escaped_output_table.h>
  17. #include <__format/formatter_output.h>
  18. #include <__format/parser_std_format_spec.h>
  19. #include <__format/unicode.h>
  20. #include <__iterator/back_insert_iterator.h>
  21. #include <__memory/addressof.h>
  22. #include <__system_error/errc.h>
  23. #include <__type_traits/make_unsigned.h>
  24. #include <__utility/move.h>
  25. #include <string_view>
  26. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  27. # pragma GCC system_header
  28. #endif
  29. _LIBCPP_BEGIN_NAMESPACE_STD
  30. namespace __formatter {
  31. #if _LIBCPP_STD_VER >= 20
  32. /// Writes a string using format's width estimation algorithm.
  33. ///
  34. /// \note When \c _LIBCPP_HAS_NO_UNICODE is defined the function assumes the
  35. /// input is ASCII.
  36. template <class _CharT>
  37. _LIBCPP_HIDE_FROM_ABI auto __write_string(
  38. basic_string_view<_CharT> __str,
  39. output_iterator<const _CharT&> auto __out_it,
  40. __format_spec::__parsed_specifications<_CharT> __specs) -> decltype(__out_it) {
  41. if (!__specs.__has_precision())
  42. return __formatter::__write_string_no_precision(__str, _VSTD::move(__out_it), __specs);
  43. int __size = __formatter::__truncate(__str, __specs.__precision_);
  44. return __formatter::__write(__str.begin(), __str.end(), _VSTD::move(__out_it), __specs, __size);
  45. }
  46. # endif // _LIBCPP_STD_VER >= 20
  47. # if _LIBCPP_STD_VER >= 23
  48. struct __nul_terminator {};
  49. template <class _CharT>
  50. _LIBCPP_HIDE_FROM_ABI bool operator==(const _CharT* __cstr, __nul_terminator) {
  51. return *__cstr == _CharT('\0');
  52. }
  53. template <class _CharT>
  54. _LIBCPP_HIDE_FROM_ABI void
  55. __write_escaped_code_unit(basic_string<_CharT>& __str, char32_t __value, const _CharT* __prefix) {
  56. back_insert_iterator __out_it{__str};
  57. std::ranges::copy(__prefix, __nul_terminator{}, __out_it);
  58. char __buffer[8];
  59. to_chars_result __r = std::to_chars(std::begin(__buffer), std::end(__buffer), __value, 16);
  60. _LIBCPP_ASSERT_UNCATEGORIZED(__r.ec == errc(0), "Internal buffer too small");
  61. std::ranges::copy(std::begin(__buffer), __r.ptr, __out_it);
  62. __str += _CharT('}');
  63. }
  64. // [format.string.escaped]/2.2.1.2
  65. // ...
  66. // then the sequence \u{hex-digit-sequence} is appended to E, where
  67. // hex-digit-sequence is the shortest hexadecimal representation of C using
  68. // lower-case hexadecimal digits.
  69. template <class _CharT>
  70. _LIBCPP_HIDE_FROM_ABI void __write_well_formed_escaped_code_unit(basic_string<_CharT>& __str, char32_t __value) {
  71. __formatter::__write_escaped_code_unit(__str, __value, _LIBCPP_STATICALLY_WIDEN(_CharT, "\\u{"));
  72. }
  73. // [format.string.escaped]/2.2.3
  74. // Otherwise (X is a sequence of ill-formed code units), each code unit U is
  75. // appended to E in order as the sequence \x{hex-digit-sequence}, where
  76. // hex-digit-sequence is the shortest hexadecimal representation of U using
  77. // lower-case hexadecimal digits.
  78. template <class _CharT>
  79. _LIBCPP_HIDE_FROM_ABI void __write_escape_ill_formed_code_unit(basic_string<_CharT>& __str, char32_t __value) {
  80. __formatter::__write_escaped_code_unit(__str, __value, _LIBCPP_STATICALLY_WIDEN(_CharT, "\\x{"));
  81. }
  82. template <class _CharT>
  83. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI bool __is_escaped_sequence_written(basic_string<_CharT>& __str, char32_t __value) {
  84. # ifdef _LIBCPP_HAS_NO_UNICODE
  85. // For ASCII assume everything above 127 is printable.
  86. if (__value > 127)
  87. return false;
  88. # endif
  89. if (!__escaped_output_table::__needs_escape(__value))
  90. return false;
  91. __formatter::__write_well_formed_escaped_code_unit(__str, __value);
  92. return true;
  93. }
  94. template <class _CharT>
  95. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr char32_t __to_char32(_CharT __value) {
  96. return static_cast<make_unsigned_t<_CharT>>(__value);
  97. }
  98. enum class __escape_quotation_mark { __apostrophe, __double_quote };
  99. // [format.string.escaped]/2
  100. template <class _CharT>
  101. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI bool
  102. __is_escaped_sequence_written(basic_string<_CharT>& __str, char32_t __value, __escape_quotation_mark __mark) {
  103. // 2.2.1.1 - Mapped character in [tab:format.escape.sequences]
  104. switch (__value) {
  105. case _CharT('\t'):
  106. __str += _LIBCPP_STATICALLY_WIDEN(_CharT, "\\t");
  107. return true;
  108. case _CharT('\n'):
  109. __str += _LIBCPP_STATICALLY_WIDEN(_CharT, "\\n");
  110. return true;
  111. case _CharT('\r'):
  112. __str += _LIBCPP_STATICALLY_WIDEN(_CharT, "\\r");
  113. return true;
  114. case _CharT('\''):
  115. if (__mark == __escape_quotation_mark::__apostrophe)
  116. __str += _LIBCPP_STATICALLY_WIDEN(_CharT, R"(\')");
  117. else
  118. __str += __value;
  119. return true;
  120. case _CharT('"'):
  121. if (__mark == __escape_quotation_mark::__double_quote)
  122. __str += _LIBCPP_STATICALLY_WIDEN(_CharT, R"(\")");
  123. else
  124. __str += __value;
  125. return true;
  126. case _CharT('\\'):
  127. __str += _LIBCPP_STATICALLY_WIDEN(_CharT, R"(\\)");
  128. return true;
  129. // 2.2.1.2 - Space
  130. case _CharT(' '):
  131. __str += __value;
  132. return true;
  133. }
  134. // 2.2.2
  135. // Otherwise, if X is a shift sequence, the effect on E and further
  136. // decoding of S is unspecified.
  137. // For now shift sequences are ignored and treated as Unicode. Other parts
  138. // of the format library do the same. It's unknown how ostream treats them.
  139. // TODO FMT determine what to do with shift sequences.
  140. // 2.2.1.2.1 and 2.2.1.2.2 - Escape
  141. return __formatter::__is_escaped_sequence_written(__str, __formatter::__to_char32(__value));
  142. }
  143. template <class _CharT>
  144. _LIBCPP_HIDE_FROM_ABI void
  145. __escape(basic_string<_CharT>& __str, basic_string_view<_CharT> __values, __escape_quotation_mark __mark) {
  146. __unicode::__code_point_view<_CharT> __view{__values.begin(), __values.end()};
  147. while (!__view.__at_end()) {
  148. auto __first = __view.__position();
  149. typename __unicode::__consume_result __result = __view.__consume();
  150. if (__result.__status == __unicode::__consume_result::__ok) {
  151. if (!__formatter::__is_escaped_sequence_written(__str, __result.__code_point, __mark))
  152. // 2.2.1.3 - Add the character
  153. ranges::copy(__first, __view.__position(), std::back_insert_iterator(__str));
  154. } else {
  155. // 2.2.3 sequence of ill-formed code units
  156. ranges::for_each(__first, __view.__position(), [&](_CharT __value) {
  157. __formatter::__write_escape_ill_formed_code_unit(__str, __formatter::__to_char32(__value));
  158. });
  159. }
  160. }
  161. }
  162. template <class _CharT>
  163. _LIBCPP_HIDE_FROM_ABI auto
  164. __format_escaped_char(_CharT __value,
  165. output_iterator<const _CharT&> auto __out_it,
  166. __format_spec::__parsed_specifications<_CharT> __specs) -> decltype(__out_it) {
  167. basic_string<_CharT> __str;
  168. __str += _CharT('\'');
  169. __formatter::__escape(__str, basic_string_view{std::addressof(__value), 1}, __escape_quotation_mark::__apostrophe);
  170. __str += _CharT('\'');
  171. return __formatter::__write(__str.data(), __str.data() + __str.size(), _VSTD::move(__out_it), __specs, __str.size());
  172. }
  173. template <class _CharT>
  174. _LIBCPP_HIDE_FROM_ABI auto
  175. __format_escaped_string(basic_string_view<_CharT> __values,
  176. output_iterator<const _CharT&> auto __out_it,
  177. __format_spec::__parsed_specifications<_CharT> __specs) -> decltype(__out_it) {
  178. basic_string<_CharT> __str;
  179. __str += _CharT('"');
  180. __formatter::__escape(__str, __values, __escape_quotation_mark::__double_quote);
  181. __str += _CharT('"');
  182. return __formatter::__write_string(basic_string_view{__str}, _VSTD::move(__out_it), __specs);
  183. }
  184. # endif // _LIBCPP_STD_VER >= 23
  185. } // namespace __formatter
  186. _LIBCPP_END_NAMESPACE_STD
  187. #endif // _LIBCPP___FORMAT_WRITE_ESCAPED_H