unicode.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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_INTERNAL(__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_INTERNAL(__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_INTERNAL(__prev != __property::__sot, "should be handled in the constructor"); // GB1
  252. _LIBCPP_ASSERT_INTERNAL(__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 && (__next == __property::__L || __next == __property::__V ||
  262. __next == __property::__LV || __next == __property::__LVT)) // GB6
  263. return false;
  264. if ((__prev == __property::__LV || __prev == __property::__V) &&
  265. (__next == __property::__V || __next == __property::__T)) // GB7
  266. return false;
  267. if ((__prev == __property::__LVT || __prev == __property::__T) && __next == __property::__T) // GB8
  268. return false;
  269. // *** Do not break before extending characters or ZWJ. ***
  270. if (__next == __property::__Extend || __next == __property::__ZWJ)
  271. return false; // GB9
  272. // *** Do not break before SpacingMarks, or after Prepend characters. ***
  273. if (__next == __property::__SpacingMark) // GB9a
  274. return false;
  275. if (__prev == __property::__Prepend) // GB9b
  276. return false;
  277. // *** Do not break within emoji modifier sequences or emoji zwj sequences. ***
  278. // GB11 \p{Extended_Pictographic} Extend* ZWJ x \p{Extended_Pictographic}
  279. //
  280. // Note that several parts of this rule are matched by GB9: Any x (Extend | ZWJ)
  281. // - \p{Extended_Pictographic} x Extend
  282. // - Extend x Extend
  283. // - \p{Extended_Pictographic} x ZWJ
  284. // - Extend x ZWJ
  285. //
  286. // So the only case left to test is
  287. // - \p{Extended_Pictographic}' x ZWJ x \p{Extended_Pictographic}
  288. // where \p{Extended_Pictographic}' is stored in __has_extened_pictographic
  289. if (__has_extened_pictographic && __prev == __property::__ZWJ && __next == __property::__Extended_Pictographic)
  290. return false;
  291. // *** Do not break within emoji flag sequences ***
  292. // That is, do not break between regional indicator (RI) symbols if there
  293. // is an odd number of RI characters before the break point.
  294. if (__prev == __property::__Regional_Indicator && __next == __property::__Regional_Indicator) { // GB12 + GB13
  295. __ri_break_allowed = !__ri_break_allowed;
  296. return __ri_break_allowed;
  297. }
  298. // *** Otherwise, break everywhere. ***
  299. return true; // GB999
  300. }
  301. /// Helper class to extract an extended grapheme cluster from a Unicode character range.
  302. ///
  303. /// This function is used to determine the column width of an extended grapheme
  304. /// cluster. In order to do that only the first code point is evaluated.
  305. /// Therefore only this code point is extracted.
  306. template <class _CharT>
  307. class __extended_grapheme_cluster_view {
  308. using _Iterator = typename basic_string_view<_CharT>::const_iterator;
  309. public:
  310. _LIBCPP_HIDE_FROM_ABI constexpr explicit __extended_grapheme_cluster_view(_Iterator __first, _Iterator __last)
  311. : __code_point_view_(__first, __last),
  312. __next_code_point_(__code_point_view_.__consume().__code_point),
  313. __next_prop_(__extended_grapheme_custer_property_boundary::__get_property(__next_code_point_)) {}
  314. struct __cluster {
  315. /// The first code point of the extended grapheme cluster.
  316. ///
  317. /// The first code point is used to estimate the width of the extended
  318. /// grapheme cluster.
  319. char32_t __code_point_;
  320. /// Points one beyond the last code unit in the extended grapheme cluster.
  321. ///
  322. /// It's expected the caller has the start position and thus can determine
  323. /// the code unit range of the extended grapheme cluster.
  324. _Iterator __last_;
  325. };
  326. _LIBCPP_HIDE_FROM_ABI constexpr __cluster __consume() {
  327. _LIBCPP_ASSERT_INTERNAL(__next_prop_ != __extended_grapheme_custer_property_boundary::__property::__eot,
  328. "can't move beyond the end of input");
  329. char32_t __code_point = __next_code_point_;
  330. if (!__code_point_view_.__at_end())
  331. return {__code_point, __get_break()};
  332. __next_prop_ = __extended_grapheme_custer_property_boundary::__property::__eot;
  333. return {__code_point, __code_point_view_.__position()};
  334. }
  335. private:
  336. __code_point_view<_CharT> __code_point_view_;
  337. char32_t __next_code_point_;
  338. __extended_grapheme_custer_property_boundary::__property __next_prop_;
  339. _LIBCPP_HIDE_FROM_ABI constexpr _Iterator __get_break() {
  340. bool __ri_break_allowed = true;
  341. bool __has_extened_pictographic = false;
  342. while (true) {
  343. _Iterator __result = __code_point_view_.__position();
  344. __extended_grapheme_custer_property_boundary::__property __prev = __next_prop_;
  345. if (__code_point_view_.__at_end()) {
  346. __next_prop_ = __extended_grapheme_custer_property_boundary::__property::__eot;
  347. return __result;
  348. }
  349. __next_code_point_ = __code_point_view_.__consume().__code_point;
  350. __next_prop_ = __extended_grapheme_custer_property_boundary::__get_property(__next_code_point_);
  351. __has_extened_pictographic |=
  352. __prev == __extended_grapheme_custer_property_boundary::__property::__Extended_Pictographic;
  353. if (__at_extended_grapheme_cluster_break(__ri_break_allowed, __has_extened_pictographic, __prev, __next_prop_))
  354. return __result;
  355. }
  356. }
  357. };
  358. template <contiguous_iterator _Iterator>
  359. __extended_grapheme_cluster_view(_Iterator, _Iterator) -> __extended_grapheme_cluster_view<iter_value_t<_Iterator>>;
  360. # else // _LIBCPP_HAS_NO_UNICODE
  361. // For ASCII every character is a "code point".
  362. // This makes it easier to write code agnostic of the _LIBCPP_HAS_NO_UNICODE define.
  363. template <class _CharT>
  364. class __code_point_view {
  365. using _Iterator = typename basic_string_view<_CharT>::const_iterator;
  366. public:
  367. _LIBCPP_HIDE_FROM_ABI constexpr explicit __code_point_view(_Iterator __first, _Iterator __last)
  368. : __first_(__first), __last_(__last) {}
  369. _LIBCPP_HIDE_FROM_ABI constexpr bool __at_end() const noexcept { return __first_ == __last_; }
  370. _LIBCPP_HIDE_FROM_ABI constexpr _Iterator __position() const noexcept { return __first_; }
  371. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __consume_result __consume() noexcept {
  372. _LIBCPP_ASSERT_INTERNAL(__first_ != __last_, "can't move beyond the end of input");
  373. return {static_cast<char32_t>(*__first_++)};
  374. }
  375. private:
  376. _Iterator __first_;
  377. _Iterator __last_;
  378. };
  379. # endif // _LIBCPP_HAS_NO_UNICODE
  380. } // namespace __unicode
  381. #endif //_LIBCPP_STD_VER >= 20
  382. _LIBCPP_END_NAMESPACE_STD
  383. #endif // _LIBCPP___FORMAT_UNICODE_H