unicode.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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_UNICODE_H
  10. #define _LIBCPP___FORMAT_UNICODE_H
  11. #include <__assert>
  12. #include <__bit/countl.h>
  13. #include <__concepts/same_as.h>
  14. #include <__config>
  15. #include <__format/extended_grapheme_cluster_table.h>
  16. #include <__iterator/concepts.h>
  17. #include <__iterator/readable_traits.h> // iter_value_t
  18. #include <string_view>
  19. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  20. # pragma GCC system_header
  21. #endif
  22. _LIBCPP_BEGIN_NAMESPACE_STD
  23. #if _LIBCPP_STD_VER >= 20
  24. namespace __unicode {
  25. // Helper struct for the result of a consume operation.
  26. //
  27. // The status value for a correct code point is 0. This allows a valid value to
  28. // be used without masking.
  29. // When the decoding fails it know the number of code units affected. For the
  30. // current use-cases that value is not needed, therefore it is not stored.
  31. // The escape routine needs the number of code units for both a valid and
  32. // invalid character and keeps track of it itself. Doing it in this result
  33. // unconditionally would give some overhead when the value is unneeded.
  34. struct __consume_result {
  35. // When __status == __ok it contains the decoded code point.
  36. // Else it contains the replacement character U+FFFD
  37. char32_t __code_point : 31;
  38. enum : char32_t {
  39. // Consumed a well-formed code point.
  40. __ok = 0,
  41. // Encountered invalid UTF-8
  42. __error = 1
  43. } __status : 1 {__ok};
  44. };
  45. static_assert(sizeof(__consume_result) == sizeof(char32_t));
  46. # ifndef _LIBCPP_HAS_NO_UNICODE
  47. /// Implements the grapheme cluster boundary rules
  48. ///
  49. /// These rules are used to implement format's width estimation as stated in
  50. /// [format.string.std]/11
  51. ///
  52. /// The Standard refers to UAX \#29 for Unicode 12.0.0
  53. /// https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
  54. ///
  55. /// The data tables used are
  56. /// https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt
  57. /// https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt
  58. /// https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.txt (for testing only)
  59. inline constexpr char32_t __replacement_character = U'\ufffd';
  60. // The error of a consume operation.
  61. //
  62. // This sets the code point to the replacement character. This code point does
  63. // not participate in the grapheme clustering, so grapheme clustering code can
  64. // ignore the error status and always use the code point.
  65. inline constexpr __consume_result __consume_result_error{__replacement_character, __consume_result::__error};
  66. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool __is_high_surrogate(char32_t __value) {
  67. return __value >= 0xd800 && __value <= 0xdbff;
  68. }
  69. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool __is_low_surrogate(char32_t __value) {
  70. return __value >= 0xdc00 && __value <= 0xdfff;
  71. }
  72. // https://www.unicode.org/glossary/#surrogate_code_point
  73. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline constexpr bool __is_surrogate(char32_t __value) {
  74. return __value >= 0xd800 && __value <= 0xdfff;
  75. }
  76. // https://www.unicode.org/glossary/#code_point
  77. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline constexpr bool __is_code_point(char32_t __value) {
  78. return __value <= 0x10ffff;
  79. }
  80. // https://www.unicode.org/glossary/#unicode_scalar_value
  81. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI inline constexpr bool __is_scalar_value(char32_t __value) {
  82. return __unicode::__is_code_point(__value) && !__unicode::__is_surrogate(__value);
  83. }
  84. template <contiguous_iterator _Iterator>
  85. requires same_as<iter_value_t<_Iterator>, char>
  86. _LIBCPP_HIDE_FROM_ABI constexpr bool __is_continuation(_Iterator __char, int __count) {
  87. do {
  88. if ((*__char & 0b1100'0000) != 0b1000'0000)
  89. return false;
  90. --__count;
  91. ++__char;
  92. } while (__count);
  93. return true;
  94. }
  95. /// Helper class to extract a code unit from a Unicode character range.
  96. ///
  97. /// The stored range is a view. There are multiple specialization for different
  98. /// character types.
  99. template <class _CharT>
  100. class __code_point_view;
  101. /// UTF-8 specialization.
  102. template <>
  103. class __code_point_view<char> {
  104. using _Iterator = basic_string_view<char>::const_iterator;
  105. public:
  106. _LIBCPP_HIDE_FROM_ABI constexpr explicit __code_point_view(_Iterator __first, _Iterator __last)
  107. : __first_(__first), __last_(__last) {}
  108. _LIBCPP_HIDE_FROM_ABI constexpr bool __at_end() const noexcept { return __first_ == __last_; }
  109. _LIBCPP_HIDE_FROM_ABI constexpr _Iterator __position() const noexcept { return __first_; }
  110. // https://www.unicode.org/versions/latest/ch03.pdf#G7404
  111. // Based on Table 3-7, Well-Formed UTF-8 Byte Sequences
  112. //
  113. // Code Points First Byte Second Byte Third Byte Fourth Byte Remarks
  114. // U+0000..U+007F 00..7F U+0000..U+007F 1 code unit range
  115. // C0..C1 80..BF invalid overlong encoding
  116. // U+0080..U+07FF C2..DF 80..BF U+0080..U+07FF 2 code unit range
  117. // E0 80..9F 80..BF invalid overlong encoding
  118. // U+0800..U+0FFF E0 A0..BF 80..BF U+0800..U+FFFF 3 code unit range
  119. // U+1000..U+CFFF E1..EC 80..BF 80..BF
  120. // U+D000..U+D7FF ED 80..9F 80..BF
  121. // U+D800..U+DFFF ED A0..BF 80..BF invalid encoding of surrogate code point
  122. // U+E000..U+FFFF EE..EF 80..BF 80..BF
  123. // F0 80..8F 80..BF 80..BF invalid overlong encoding
  124. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF U+10000..U+10FFFF 4 code unit range
  125. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  126. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  127. // F4 90..BF 80..BF 80..BF U+110000.. invalid code point range
  128. //
  129. // Unlike other parsers, these invalid entries are tested after decoding.
  130. // - The parser always needs to consume these code units
  131. // - The code is optimized for well-formed UTF-8
  132. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __consume_result __consume() noexcept {
  133. _LIBCPP_ASSERT_UNCATEGORIZED(__first_ != __last_, "can't move beyond the end of input");
  134. // Based on the number of leading 1 bits the number of code units in the
  135. // code point can be determined. See
  136. // https://en.wikipedia.org/wiki/UTF-8#Encoding
  137. switch (std::countl_one(static_cast<unsigned char>(*__first_))) {
  138. case 0:
  139. return {static_cast<unsigned char>(*__first_++)};
  140. case 2: {
  141. if (__last_ - __first_ < 2 || !__unicode::__is_continuation(__first_ + 1, 1)) [[unlikely]]
  142. break;
  143. char32_t __value = static_cast<unsigned char>(*__first_++) & 0x1f;
  144. __value <<= 6;
  145. __value |= static_cast<unsigned char>(*__first_++) & 0x3f;
  146. // These values should be encoded in 1 UTF-8 code unit.
  147. if (__value < 0x0080) [[unlikely]]
  148. return __consume_result_error;
  149. return {__value};
  150. }
  151. case 3: {
  152. if (__last_ - __first_ < 3 || !__unicode::__is_continuation(__first_ + 1, 2)) [[unlikely]]
  153. break;
  154. char32_t __value = static_cast<unsigned char>(*__first_++) & 0x0f;
  155. __value <<= 6;
  156. __value |= static_cast<unsigned char>(*__first_++) & 0x3f;
  157. __value <<= 6;
  158. __value |= static_cast<unsigned char>(*__first_++) & 0x3f;
  159. // These values should be encoded in 1 or 2 UTF-8 code units.
  160. if (__value < 0x0800) [[unlikely]]
  161. return __consume_result_error;
  162. // A surrogate value is always encoded in 3 UTF-8 code units.
  163. if (__unicode::__is_surrogate(__value)) [[unlikely]]
  164. return __consume_result_error;
  165. return {__value};
  166. }
  167. case 4: {
  168. if (__last_ - __first_ < 4 || !__unicode::__is_continuation(__first_ + 1, 3)) [[unlikely]]
  169. break;
  170. char32_t __value = static_cast<unsigned char>(*__first_++) & 0x07;
  171. __value <<= 6;
  172. __value |= static_cast<unsigned char>(*__first_++) & 0x3f;
  173. __value <<= 6;
  174. __value |= static_cast<unsigned char>(*__first_++) & 0x3f;
  175. __value <<= 6;
  176. __value |= static_cast<unsigned char>(*__first_++) & 0x3f;
  177. // These values should be encoded in 1, 2, or 3 UTF-8 code units.
  178. if (__value < 0x10000) [[unlikely]]
  179. return __consume_result_error;
  180. // A value too large is always encoded in 4 UTF-8 code units.
  181. if (!__unicode::__is_code_point(__value)) [[unlikely]]
  182. return __consume_result_error;
  183. return {__value};
  184. }
  185. }
  186. // An invalid number of leading ones can be garbage or a code unit in the
  187. // middle of a code point. By consuming one code unit the parser may get
  188. // "in sync" after a few code units.
  189. ++__first_;
  190. return __consume_result_error;
  191. }
  192. private:
  193. _Iterator __first_;
  194. _Iterator __last_;
  195. };
  196. # ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
  197. _LIBCPP_HIDE_FROM_ABI constexpr bool __is_surrogate_pair_high(wchar_t __value) {
  198. return __value >= 0xd800 && __value <= 0xdbff;
  199. }
  200. _LIBCPP_HIDE_FROM_ABI constexpr bool __is_surrogate_pair_low(wchar_t __value) {
  201. return __value >= 0xdc00 && __value <= 0xdfff;
  202. }
  203. /// This specialization depends on the size of wchar_t
  204. /// - 2 UTF-16 (for example Windows and AIX)
  205. /// - 4 UTF-32 (for example Linux)
  206. template <>
  207. class __code_point_view<wchar_t> {
  208. using _Iterator = typename basic_string_view<wchar_t>::const_iterator;
  209. public:
  210. static_assert(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4, "sizeof(wchar_t) has a not implemented value");
  211. _LIBCPP_HIDE_FROM_ABI constexpr explicit __code_point_view(_Iterator __first, _Iterator __last)
  212. : __first_(__first), __last_(__last) {}
  213. _LIBCPP_HIDE_FROM_ABI constexpr _Iterator __position() const noexcept { return __first_; }
  214. _LIBCPP_HIDE_FROM_ABI constexpr bool __at_end() const noexcept { return __first_ == __last_; }
  215. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __consume_result __consume() noexcept {
  216. _LIBCPP_ASSERT_UNCATEGORIZED(__first_ != __last_, "can't move beyond the end of input");
  217. char32_t __value = static_cast<char32_t>(*__first_++);
  218. if constexpr (sizeof(wchar_t) == 2) {
  219. if (__unicode::__is_low_surrogate(__value)) [[unlikely]]
  220. return __consume_result_error;
  221. if (__unicode::__is_high_surrogate(__value)) {
  222. if (__first_ == __last_ || !__unicode::__is_low_surrogate(static_cast<char32_t>(*__first_))) [[unlikely]]
  223. return __consume_result_error;
  224. __value -= 0xd800;
  225. __value <<= 10;
  226. __value += static_cast<char32_t>(*__first_++) - 0xdc00;
  227. __value += 0x10000;
  228. if (!__unicode::__is_code_point(__value)) [[unlikely]]
  229. return __consume_result_error;
  230. }
  231. } else {
  232. if (!__unicode::__is_scalar_value(__value)) [[unlikely]]
  233. return __consume_result_error;
  234. }
  235. return {__value};
  236. }
  237. private:
  238. _Iterator __first_;
  239. _Iterator __last_;
  240. };
  241. # endif // _LIBCPP_HAS_NO_WIDE_CHARACTERS
  242. _LIBCPP_HIDE_FROM_ABI constexpr bool __at_extended_grapheme_cluster_break(
  243. bool& __ri_break_allowed,
  244. bool __has_extened_pictographic,
  245. __extended_grapheme_custer_property_boundary::__property __prev,
  246. __extended_grapheme_custer_property_boundary::__property __next) {
  247. using __extended_grapheme_custer_property_boundary::__property;
  248. __has_extened_pictographic |= __prev == __property::__Extended_Pictographic;
  249. // https://www.unicode.org/reports/tr29/tr29-39.html#Grapheme_Cluster_Boundary_Rules
  250. // *** Break at the start and end of text, unless the text is empty. ***
  251. _LIBCPP_ASSERT_UNCATEGORIZED(__prev != __property::__sot, "should be handled in the constructor"); // GB1
  252. _LIBCPP_ASSERT_UNCATEGORIZED(__prev != __property::__eot, "should be handled by our caller"); // GB2
  253. // *** Do not break between a CR and LF. Otherwise, break before and after controls. ***
  254. if (__prev == __property::__CR && __next == __property::__LF) // GB3
  255. return false;
  256. if (__prev == __property::__Control || __prev == __property::__CR || __prev == __property::__LF) // GB4
  257. return true;
  258. if (__next == __property::__Control || __next == __property::__CR || __next == __property::__LF) // GB5
  259. return true;
  260. // *** Do not break Hangul syllable sequences. ***
  261. if (__prev == __property::__L &&
  262. (__next == __property::__L || __next == __property::__V || __next == __property::__LV ||
  263. __next == __property::__LVT)) // GB6
  264. return false;
  265. if ((__prev == __property::__LV || __prev == __property::__V) &&
  266. (__next == __property::__V || __next == __property::__T)) // GB7
  267. return false;
  268. if ((__prev == __property::__LVT || __prev == __property::__T) && __next == __property::__T) // GB8
  269. return false;
  270. // *** Do not break before extending characters or ZWJ. ***
  271. if (__next == __property::__Extend || __next == __property::__ZWJ)
  272. return false; // GB9
  273. // *** Do not break before SpacingMarks, or after Prepend characters. ***
  274. if (__next == __property::__SpacingMark) // GB9a
  275. return false;
  276. if (__prev == __property::__Prepend) // GB9b
  277. return false;
  278. // *** Do not break within emoji modifier sequences or emoji zwj sequences. ***
  279. // GB11 \p{Extended_Pictographic} Extend* ZWJ x \p{Extended_Pictographic}
  280. //
  281. // Note that several parts of this rule are matched by GB9: Any x (Extend | ZWJ)
  282. // - \p{Extended_Pictographic} x Extend
  283. // - Extend x Extend
  284. // - \p{Extended_Pictographic} x ZWJ
  285. // - Extend x ZWJ
  286. //
  287. // So the only case left to test is
  288. // - \p{Extended_Pictographic}' x ZWJ x \p{Extended_Pictographic}
  289. // where \p{Extended_Pictographic}' is stored in __has_extened_pictographic
  290. if (__has_extened_pictographic && __prev == __property::__ZWJ && __next == __property::__Extended_Pictographic)
  291. return false;
  292. // *** Do not break within emoji flag sequences ***
  293. // That is, do not break between regional indicator (RI) symbols if there
  294. // is an odd number of RI characters before the break point.
  295. if (__prev == __property::__Regional_Indicator && __next == __property::__Regional_Indicator) { // GB12 + GB13
  296. __ri_break_allowed = !__ri_break_allowed;
  297. return __ri_break_allowed;
  298. }
  299. // *** Otherwise, break everywhere. ***
  300. return true; // GB999
  301. }
  302. /// Helper class to extract an extended grapheme cluster from a Unicode character range.
  303. ///
  304. /// This function is used to determine the column width of an extended grapheme
  305. /// cluster. In order to do that only the first code point is evaluated.
  306. /// Therefore only this code point is extracted.
  307. template <class _CharT>
  308. class __extended_grapheme_cluster_view {
  309. using _Iterator = typename basic_string_view<_CharT>::const_iterator;
  310. public:
  311. _LIBCPP_HIDE_FROM_ABI constexpr explicit __extended_grapheme_cluster_view(_Iterator __first, _Iterator __last)
  312. : __code_point_view_(__first, __last),
  313. __next_code_point_(__code_point_view_.__consume().__code_point),
  314. __next_prop_(__extended_grapheme_custer_property_boundary::__get_property(__next_code_point_)) {}
  315. struct __cluster {
  316. /// The first code point of the extended grapheme cluster.
  317. ///
  318. /// The first code point is used to estimate the width of the extended
  319. /// grapheme cluster.
  320. char32_t __code_point_;
  321. /// Points one beyond the last code unit in the extended grapheme cluster.
  322. ///
  323. /// It's expected the caller has the start position and thus can determine
  324. /// the code unit range of the extended grapheme cluster.
  325. _Iterator __last_;
  326. };
  327. _LIBCPP_HIDE_FROM_ABI constexpr __cluster __consume() {
  328. _LIBCPP_ASSERT_UNCATEGORIZED(
  329. __next_prop_ != __extended_grapheme_custer_property_boundary::__property::__eot,
  330. "can't move beyond the end of input");
  331. char32_t __code_point = __next_code_point_;
  332. if (!__code_point_view_.__at_end())
  333. return {__code_point, __get_break()};
  334. __next_prop_ = __extended_grapheme_custer_property_boundary::__property::__eot;
  335. return {__code_point, __code_point_view_.__position()};
  336. }
  337. private:
  338. __code_point_view<_CharT> __code_point_view_;
  339. char32_t __next_code_point_;
  340. __extended_grapheme_custer_property_boundary::__property __next_prop_;
  341. _LIBCPP_HIDE_FROM_ABI constexpr _Iterator __get_break() {
  342. bool __ri_break_allowed = true;
  343. bool __has_extened_pictographic = false;
  344. while (true) {
  345. _Iterator __result = __code_point_view_.__position();
  346. __extended_grapheme_custer_property_boundary::__property __prev = __next_prop_;
  347. if (__code_point_view_.__at_end()) {
  348. __next_prop_ = __extended_grapheme_custer_property_boundary::__property::__eot;
  349. return __result;
  350. }
  351. __next_code_point_ = __code_point_view_.__consume().__code_point;
  352. __next_prop_ = __extended_grapheme_custer_property_boundary::__get_property(__next_code_point_);
  353. __has_extened_pictographic |=
  354. __prev == __extended_grapheme_custer_property_boundary::__property::__Extended_Pictographic;
  355. if (__at_extended_grapheme_cluster_break(__ri_break_allowed, __has_extened_pictographic, __prev, __next_prop_))
  356. return __result;
  357. }
  358. }
  359. };
  360. template <contiguous_iterator _Iterator>
  361. __extended_grapheme_cluster_view(_Iterator, _Iterator) -> __extended_grapheme_cluster_view<iter_value_t<_Iterator>>;
  362. # else // _LIBCPP_HAS_NO_UNICODE
  363. // For ASCII every character is a "code point".
  364. // This makes it easier to write code agnostic of the _LIBCPP_HAS_NO_UNICODE define.
  365. template <class _CharT>
  366. class __code_point_view {
  367. using _Iterator = typename basic_string_view<_CharT>::const_iterator;
  368. public:
  369. _LIBCPP_HIDE_FROM_ABI constexpr explicit __code_point_view(_Iterator __first, _Iterator __last)
  370. : __first_(__first), __last_(__last) {}
  371. _LIBCPP_HIDE_FROM_ABI constexpr bool __at_end() const noexcept { return __first_ == __last_; }
  372. _LIBCPP_HIDE_FROM_ABI constexpr _Iterator __position() const noexcept { return __first_; }
  373. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __consume_result __consume() noexcept {
  374. _LIBCPP_ASSERT_UNCATEGORIZED(__first_ != __last_, "can't move beyond the end of input");
  375. return {static_cast<char32_t>(*__first_++)};
  376. }
  377. private:
  378. _Iterator __first_;
  379. _Iterator __last_;
  380. };
  381. # endif // _LIBCPP_HAS_NO_UNICODE
  382. } // namespace __unicode
  383. #endif //_LIBCPP_STD_VER >= 20
  384. _LIBCPP_END_NAMESPACE_STD
  385. #endif // _LIBCPP___FORMAT_UNICODE_H