GenerateUnicodeData.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "GeneratorUtil.h"
  7. #include <AK/AllOf.h>
  8. #include <AK/Array.h>
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Find.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/Optional.h>
  13. #include <AK/QuickSort.h>
  14. #include <AK/SourceGenerator.h>
  15. #include <AK/String.h>
  16. #include <AK/StringUtils.h>
  17. #include <AK/Types.h>
  18. #include <AK/Vector.h>
  19. #include <LibCore/ArgsParser.h>
  20. #include <LibCore/Stream.h>
  21. using StringIndexType = u16;
  22. constexpr auto s_string_index_type = "u16"sv;
  23. // Some code points are excluded from UnicodeData.txt, and instead are part of a "range" of code
  24. // points, as indicated by the "name" field. For example:
  25. // 3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;
  26. // 4DBF;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;
  27. struct CodePointRange {
  28. u32 first;
  29. u32 last;
  30. };
  31. // SpecialCasing source: https://www.unicode.org/Public/13.0.0/ucd/SpecialCasing.txt
  32. // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#SpecialCasing.txt
  33. struct SpecialCasing {
  34. u32 index { 0 };
  35. u32 code_point { 0 };
  36. Vector<u32> lowercase_mapping;
  37. Vector<u32> uppercase_mapping;
  38. Vector<u32> titlecase_mapping;
  39. String locale;
  40. String condition;
  41. };
  42. // PropList source: https://www.unicode.org/Public/13.0.0/ucd/PropList.txt
  43. // Property descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#PropList.txt
  44. using PropList = HashMap<String, Vector<CodePointRange>>;
  45. // Normalization source: https://www.unicode.org/Public/13.0.0/ucd/DerivedNormalizationProps.txt
  46. // Normalization descriptions: https://www.unicode.org/reports/tr44/#DerivedNormalizationProps.txt
  47. enum class QuickCheck {
  48. Yes,
  49. No,
  50. Maybe,
  51. };
  52. struct Normalization {
  53. CodePointRange code_point_range;
  54. Vector<u32> value;
  55. QuickCheck quick_check { QuickCheck::Yes };
  56. };
  57. using NormalizationProps = HashMap<String, Vector<Normalization>>;
  58. struct CodePointName {
  59. CodePointRange code_point_range;
  60. StringIndexType name { 0 };
  61. };
  62. // UnicodeData source: https://www.unicode.org/Public/13.0.0/ucd/UnicodeData.txt
  63. // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#UnicodeData.txt
  64. // https://www.unicode.org/reports/tr44/#General_Category_Values
  65. struct CodePointData {
  66. u32 code_point { 0 };
  67. String name;
  68. Optional<StringIndexType> abbreviation;
  69. u8 canonical_combining_class { 0 };
  70. String bidi_class;
  71. String decomposition_type;
  72. Optional<i8> numeric_value_decimal;
  73. Optional<i8> numeric_value_digit;
  74. Optional<i8> numeric_value_numeric;
  75. bool bidi_mirrored { false };
  76. String unicode_1_name;
  77. String iso_comment;
  78. Optional<u32> simple_uppercase_mapping;
  79. Optional<u32> simple_lowercase_mapping;
  80. Optional<u32> simple_titlecase_mapping;
  81. Vector<u32> special_casing_indices;
  82. };
  83. struct BlockName {
  84. CodePointRange code_point_range;
  85. StringIndexType name { 0 };
  86. };
  87. struct UnicodeData {
  88. UniqueStringStorage<StringIndexType> unique_strings;
  89. u32 code_points_with_non_zero_combining_class { 0 };
  90. u32 simple_uppercase_mapping_size { 0 };
  91. u32 simple_lowercase_mapping_size { 0 };
  92. Vector<SpecialCasing> special_casing;
  93. u32 code_points_with_special_casing { 0 };
  94. u32 largest_casing_transform_size { 0 };
  95. u32 largest_special_casing_size { 0 };
  96. Vector<String> conditions;
  97. Vector<CodePointData> code_point_data;
  98. HashMap<u32, StringIndexType> code_point_abbreviations;
  99. HashMap<u32, StringIndexType> code_point_display_name_aliases;
  100. Vector<CodePointName> code_point_display_names;
  101. PropList general_categories;
  102. Vector<Alias> general_category_aliases;
  103. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  104. // any UCD file. Assigned code point ranges are derived as this generator is executed.
  105. // https://unicode.org/reports/tr18/#General_Category_Property
  106. PropList prop_list {
  107. { "Any"sv, { { 0, 0x10ffff } } },
  108. { "Assigned"sv, {} },
  109. { "ASCII"sv, { { 0, 0x7f } } },
  110. };
  111. Vector<Alias> prop_aliases;
  112. PropList script_list {
  113. { "Unknown"sv, {} },
  114. };
  115. Vector<Alias> script_aliases;
  116. PropList script_extensions;
  117. PropList block_list {
  118. { "No_Block"sv, {} },
  119. };
  120. Vector<Alias> block_aliases;
  121. Vector<BlockName> block_display_names;
  122. // FIXME: We are not yet doing anything with this data. It will be needed for String.prototype.normalize.
  123. NormalizationProps normalization_props;
  124. PropList grapheme_break_props;
  125. PropList word_break_props;
  126. PropList sentence_break_props;
  127. };
  128. static String sanitize_entry(String const& entry)
  129. {
  130. auto sanitized = entry.replace("-"sv, "_"sv, ReplaceMode::All);
  131. sanitized = sanitized.replace(" "sv, "_"sv, ReplaceMode::All);
  132. StringBuilder builder;
  133. bool next_is_upper = true;
  134. for (auto ch : sanitized) {
  135. if (next_is_upper)
  136. builder.append_code_point(to_ascii_uppercase(ch));
  137. else
  138. builder.append_code_point(ch);
  139. next_is_upper = ch == '_';
  140. }
  141. return builder.to_string();
  142. }
  143. static Vector<u32> parse_code_point_list(StringView list)
  144. {
  145. Vector<u32> code_points;
  146. auto segments = list.split_view(' ');
  147. for (auto const& code_point : segments)
  148. code_points.append(AK::StringUtils::convert_to_uint_from_hex<u32>(code_point).value());
  149. return code_points;
  150. }
  151. static CodePointRange parse_code_point_range(StringView list)
  152. {
  153. CodePointRange code_point_range {};
  154. if (list.contains(".."sv)) {
  155. auto segments = list.split_view(".."sv);
  156. VERIFY(segments.size() == 2);
  157. auto begin = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  158. auto end = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[1]).value();
  159. code_point_range = { begin, end };
  160. } else {
  161. auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(list).value();
  162. code_point_range = { code_point, code_point };
  163. }
  164. return code_point_range;
  165. }
  166. static ErrorOr<void> parse_special_casing(Core::Stream::BufferedFile& file, UnicodeData& unicode_data)
  167. {
  168. Array<u8, 1024> buffer;
  169. while (TRY(file.can_read_line())) {
  170. auto line = TRY(file.read_line(buffer));
  171. if (line.is_empty() || line.starts_with('#'))
  172. continue;
  173. if (auto index = line.find('#'); index.has_value())
  174. line = line.substring_view(0, *index);
  175. auto segments = line.split_view(';', true);
  176. VERIFY(segments.size() == 5 || segments.size() == 6);
  177. SpecialCasing casing {};
  178. casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  179. casing.lowercase_mapping = parse_code_point_list(segments[1]);
  180. casing.titlecase_mapping = parse_code_point_list(segments[2]);
  181. casing.uppercase_mapping = parse_code_point_list(segments[3]);
  182. if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
  183. auto conditions = condition.split_view(' ', true);
  184. VERIFY(conditions.size() == 1 || conditions.size() == 2);
  185. if (conditions.size() == 2) {
  186. casing.locale = conditions[0];
  187. casing.condition = conditions[1];
  188. } else if (all_of(conditions[0], is_ascii_lower_alpha)) {
  189. casing.locale = conditions[0];
  190. } else {
  191. casing.condition = conditions[0];
  192. }
  193. if (!casing.locale.is_empty())
  194. casing.locale = String::formatted("{:c}{}", to_ascii_uppercase(casing.locale[0]), casing.locale.substring_view(1));
  195. casing.condition = casing.condition.replace("_"sv, ""sv, ReplaceMode::All);
  196. if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
  197. unicode_data.conditions.append(casing.condition);
  198. }
  199. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.lowercase_mapping.size());
  200. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.titlecase_mapping.size());
  201. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.uppercase_mapping.size());
  202. unicode_data.special_casing.append(move(casing));
  203. }
  204. quick_sort(unicode_data.special_casing, [](auto const& lhs, auto const& rhs) {
  205. if (lhs.code_point != rhs.code_point)
  206. return lhs.code_point < rhs.code_point;
  207. if (lhs.locale.is_empty() && !rhs.locale.is_empty())
  208. return false;
  209. if (!lhs.locale.is_empty() && rhs.locale.is_empty())
  210. return true;
  211. return lhs.locale < rhs.locale;
  212. });
  213. for (u32 i = 0; i < unicode_data.special_casing.size(); ++i)
  214. unicode_data.special_casing[i].index = i;
  215. return {};
  216. }
  217. static ErrorOr<void> parse_prop_list(Core::Stream::BufferedFile& file, PropList& prop_list, bool multi_value_property = false, bool sanitize_property = false)
  218. {
  219. Array<u8, 1024> buffer;
  220. while (TRY(file.can_read_line())) {
  221. auto line = TRY(file.read_line(buffer));
  222. if (line.is_empty() || line.starts_with('#'))
  223. continue;
  224. if (auto index = line.find('#'); index.has_value())
  225. line = line.substring_view(0, *index);
  226. auto segments = line.split_view(';', true);
  227. VERIFY(segments.size() == 2);
  228. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  229. Vector<StringView> properties;
  230. if (multi_value_property)
  231. properties = segments[1].trim_whitespace().split_view(' ');
  232. else
  233. properties = { segments[1].trim_whitespace() };
  234. for (auto& property : properties) {
  235. auto& code_points = prop_list.ensure(sanitize_property ? sanitize_entry(property).trim_whitespace().view() : property.trim_whitespace());
  236. code_points.append(code_point_range);
  237. }
  238. }
  239. return {};
  240. }
  241. static ErrorOr<void> parse_alias_list(Core::Stream::BufferedFile& file, PropList const& prop_list, Vector<Alias>& prop_aliases)
  242. {
  243. String current_property;
  244. Array<u8, 1024> buffer;
  245. auto append_alias = [&](auto alias, auto property) {
  246. // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip.
  247. if (alias == property)
  248. return;
  249. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  250. if (!prop_list.contains(property))
  251. return;
  252. prop_aliases.append({ property, alias });
  253. };
  254. while (TRY(file.can_read_line())) {
  255. auto line = TRY(file.read_line(buffer));
  256. if (line.is_empty() || line.starts_with('#')) {
  257. if (line.ends_with("Properties"sv))
  258. current_property = line.substring_view(2);
  259. continue;
  260. }
  261. // Note: For now, we only care about Binary Property aliases for Unicode property escapes.
  262. if (current_property != "Binary Properties"sv)
  263. continue;
  264. auto segments = line.split_view(';', true);
  265. VERIFY((segments.size() == 2) || (segments.size() == 3));
  266. auto alias = segments[0].trim_whitespace();
  267. auto property = segments[1].trim_whitespace();
  268. append_alias(alias, property);
  269. if (segments.size() == 3) {
  270. alias = segments[2].trim_whitespace();
  271. append_alias(alias, property);
  272. }
  273. }
  274. return {};
  275. }
  276. static ErrorOr<void> parse_name_aliases(Core::Stream::BufferedFile& file, UnicodeData& unicode_data)
  277. {
  278. Array<u8, 1024> buffer;
  279. while (TRY(file.can_read_line())) {
  280. auto line = TRY(file.read_line(buffer));
  281. if (line.is_empty() || line.starts_with('#'))
  282. continue;
  283. auto segments = line.split_view(';', true);
  284. VERIFY(segments.size() == 3);
  285. auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0].trim_whitespace());
  286. auto alias = segments[1].trim_whitespace();
  287. auto reason = segments[2].trim_whitespace();
  288. if (reason == "abbreviation"sv) {
  289. auto index = unicode_data.unique_strings.ensure(alias);
  290. unicode_data.code_point_abbreviations.set(*code_point, index);
  291. } else if (reason.is_one_of("correction"sv, "control"sv)) {
  292. if (!unicode_data.code_point_display_name_aliases.contains(*code_point)) {
  293. auto index = unicode_data.unique_strings.ensure(alias);
  294. unicode_data.code_point_display_name_aliases.set(*code_point, index);
  295. }
  296. }
  297. }
  298. return {};
  299. }
  300. static ErrorOr<void> parse_value_alias_list(Core::Stream::BufferedFile& file, StringView desired_category, Vector<String> const& value_list, Vector<Alias>& prop_aliases, bool primary_value_is_first = true, bool sanitize_alias = false)
  301. {
  302. TRY(file.seek(0, Core::Stream::SeekMode::SetPosition));
  303. Array<u8, 1024> buffer;
  304. auto append_alias = [&](auto alias, auto value) {
  305. // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip.
  306. if (alias == value)
  307. return;
  308. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  309. if (!value_list.contains_slow(value))
  310. return;
  311. prop_aliases.append({ value, alias });
  312. };
  313. while (TRY(file.can_read_line())) {
  314. auto line = TRY(file.read_line(buffer));
  315. if (line.is_empty() || line.starts_with('#'))
  316. continue;
  317. if (auto index = line.find('#'); index.has_value())
  318. line = line.substring_view(0, *index);
  319. auto segments = line.split_view(';', true);
  320. auto category = segments[0].trim_whitespace();
  321. if (category != desired_category)
  322. continue;
  323. VERIFY((segments.size() == 3) || (segments.size() == 4));
  324. auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace();
  325. auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace();
  326. append_alias(sanitize_alias ? sanitize_entry(alias).view() : alias, value);
  327. if (segments.size() == 4) {
  328. alias = segments[3].trim_whitespace();
  329. append_alias(sanitize_alias ? sanitize_entry(alias).view() : alias, value);
  330. }
  331. }
  332. return {};
  333. }
  334. static ErrorOr<void> parse_normalization_props(Core::Stream::BufferedFile& file, UnicodeData& unicode_data)
  335. {
  336. Array<u8, 1024> buffer;
  337. while (TRY(file.can_read_line())) {
  338. auto line = TRY(file.read_line(buffer));
  339. if (line.is_empty() || line.starts_with('#'))
  340. continue;
  341. if (auto index = line.find('#'); index.has_value())
  342. line = line.substring_view(0, *index);
  343. auto segments = line.split_view(';', true);
  344. VERIFY((segments.size() == 2) || (segments.size() == 3));
  345. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  346. auto property = segments[1].trim_whitespace().to_string();
  347. Vector<u32> value;
  348. QuickCheck quick_check = QuickCheck::Yes;
  349. if (segments.size() == 3) {
  350. auto value_or_quick_check = segments[2].trim_whitespace();
  351. if ((value_or_quick_check == "N"sv))
  352. quick_check = QuickCheck::No;
  353. else if ((value_or_quick_check == "M"sv))
  354. quick_check = QuickCheck::Maybe;
  355. else
  356. value = parse_code_point_list(value_or_quick_check);
  357. }
  358. auto& normalizations = unicode_data.normalization_props.ensure(property);
  359. normalizations.append({ code_point_range, move(value), quick_check });
  360. auto& prop_list = unicode_data.prop_list.ensure(property);
  361. prop_list.append(move(code_point_range));
  362. }
  363. return {};
  364. }
  365. static void add_canonical_code_point_name(CodePointRange range, StringView name, UnicodeData& unicode_data)
  366. {
  367. // https://www.unicode.org/versions/Unicode14.0.0/ch04.pdf#G142981
  368. // FIXME: Implement the NR1 rules for Hangul syllables.
  369. struct CodePointNameFormat {
  370. CodePointRange code_point_range;
  371. StringView name;
  372. };
  373. // These code point ranges are the NR2 set of name replacements defined by Table 4-8.
  374. constexpr Array<CodePointNameFormat, 15> s_ideographic_replacements { {
  375. { { 0x3400, 0x4DBF }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  376. { { 0x4E00, 0x9FFC }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  377. { { 0xF900, 0xFA6D }, "CJK COMPATIBILITY IDEOGRAPH-{:X}"sv },
  378. { { 0xFA70, 0xFAD9 }, "CJK COMPATIBILITY IDEOGRAPH-{:X}"sv },
  379. { { 0x17000, 0x187F7 }, "TANGUT IDEOGRAPH-{:X}"sv },
  380. { { 0x18B00, 0x18CD5 }, "KHITAN SMALL SCRIPT CHARACTER-{:X}"sv },
  381. { { 0x18D00, 0x18D08 }, "TANGUT IDEOGRAPH-{:X}"sv },
  382. { { 0x1B170, 0x1B2FB }, "NUSHU CHARACTER-{:X}"sv },
  383. { { 0x20000, 0x2A6DD }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  384. { { 0x2A700, 0x2B734 }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  385. { { 0x2B740, 0x2B81D }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  386. { { 0x2B820, 0x2CEA1 }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  387. { { 0x2CEB0, 0x2EBE0 }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  388. { { 0x2F800, 0x2FA1D }, "CJK COMPATIBILITY IDEOGRAPH-{:X}"sv },
  389. { { 0x30000, 0x3134A }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  390. } };
  391. auto it = find_if(s_ideographic_replacements.begin(), s_ideographic_replacements.end(),
  392. [&](auto const& replacement) {
  393. return replacement.code_point_range.first == range.first;
  394. });
  395. if (it != s_ideographic_replacements.end()) {
  396. auto index = unicode_data.unique_strings.ensure(it->name);
  397. unicode_data.code_point_display_names.append({ it->code_point_range, index });
  398. return;
  399. }
  400. it = find_if(s_ideographic_replacements.begin(), s_ideographic_replacements.end(),
  401. [&](auto const& replacement) {
  402. return (replacement.code_point_range.first <= range.first) && (range.first <= replacement.code_point_range.last);
  403. });
  404. if (it != s_ideographic_replacements.end()) {
  405. // Drop code points that will have been captured by a range defined by the ideographic replacements.
  406. return;
  407. }
  408. if (auto alias = unicode_data.code_point_display_name_aliases.get(range.first); alias.has_value()) {
  409. // NR4 states that control code points have a null string as their name. Our implementation
  410. // uses the control code's alias as its display name.
  411. unicode_data.code_point_display_names.append({ range, *alias });
  412. return;
  413. }
  414. auto index = unicode_data.unique_strings.ensure(name);
  415. unicode_data.code_point_display_names.append({ range, index });
  416. }
  417. static ErrorOr<void> parse_block_display_names(Core::Stream::BufferedFile& file, UnicodeData& unicode_data)
  418. {
  419. Array<u8, 1024> buffer;
  420. while (TRY(file.can_read_line())) {
  421. auto line = TRY(file.read_line(buffer));
  422. if (line.is_empty() || line.starts_with('#'))
  423. continue;
  424. auto segments = line.split_view(';', true);
  425. VERIFY(segments.size() == 2);
  426. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  427. auto display_name = segments[1].trim_whitespace();
  428. auto index = unicode_data.unique_strings.ensure(display_name);
  429. unicode_data.block_display_names.append({ code_point_range, index });
  430. }
  431. TRY(file.seek(0, Core::Stream::SeekMode::SetPosition));
  432. return {};
  433. }
  434. static ErrorOr<void> parse_unicode_data(Core::Stream::BufferedFile& file, UnicodeData& unicode_data)
  435. {
  436. Optional<u32> code_point_range_start;
  437. auto& assigned_code_points = unicode_data.prop_list.find("Assigned"sv)->value;
  438. Optional<u32> assigned_code_point_range_start = 0;
  439. u32 previous_code_point = 0;
  440. Array<u8, 1024> buffer;
  441. while (TRY(file.can_read_line())) {
  442. auto line = TRY(file.read_line(buffer));
  443. if (line.is_empty())
  444. continue;
  445. auto segments = line.split_view(';', true);
  446. VERIFY(segments.size() == 15);
  447. CodePointData data {};
  448. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  449. data.name = segments[1];
  450. data.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
  451. data.bidi_class = segments[4];
  452. data.decomposition_type = segments[5];
  453. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  454. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  455. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  456. data.bidi_mirrored = segments[9] == "Y"sv;
  457. data.unicode_1_name = segments[10];
  458. data.iso_comment = segments[11];
  459. data.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
  460. data.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
  461. data.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
  462. if (auto abbreviation = unicode_data.code_point_abbreviations.get(data.code_point); abbreviation.has_value())
  463. data.abbreviation = *abbreviation;
  464. if (!assigned_code_point_range_start.has_value())
  465. assigned_code_point_range_start = data.code_point;
  466. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>"sv)) {
  467. VERIFY(!code_point_range_start.has_value() && assigned_code_point_range_start.has_value());
  468. code_point_range_start = data.code_point;
  469. data.name = data.name.substring(1, data.name.length() - 9);
  470. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  471. assigned_code_point_range_start.clear();
  472. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>"sv)) {
  473. VERIFY(code_point_range_start.has_value());
  474. CodePointRange code_point_range { *code_point_range_start, data.code_point };
  475. assigned_code_points.append(code_point_range);
  476. data.name = data.name.substring(1, data.name.length() - 8);
  477. code_point_range_start.clear();
  478. add_canonical_code_point_name(code_point_range, data.name, unicode_data);
  479. } else {
  480. add_canonical_code_point_name({ data.code_point, data.code_point }, data.name, unicode_data);
  481. if ((data.code_point > 0) && (data.code_point - previous_code_point) != 1) {
  482. VERIFY(assigned_code_point_range_start.has_value());
  483. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  484. assigned_code_point_range_start = data.code_point;
  485. }
  486. }
  487. bool has_special_casing { false };
  488. for (auto const& casing : unicode_data.special_casing) {
  489. if (casing.code_point == data.code_point) {
  490. data.special_casing_indices.append(casing.index);
  491. has_special_casing = true;
  492. }
  493. }
  494. unicode_data.code_points_with_non_zero_combining_class += data.canonical_combining_class != 0;
  495. unicode_data.simple_uppercase_mapping_size += data.simple_uppercase_mapping.has_value();
  496. unicode_data.simple_lowercase_mapping_size += data.simple_lowercase_mapping.has_value();
  497. unicode_data.code_points_with_special_casing += has_special_casing;
  498. unicode_data.largest_special_casing_size = max(unicode_data.largest_special_casing_size, data.special_casing_indices.size());
  499. previous_code_point = data.code_point;
  500. unicode_data.code_point_data.append(move(data));
  501. }
  502. return {};
  503. }
  504. static ErrorOr<void> generate_unicode_data_header(Core::Stream::BufferedFile& file, UnicodeData& unicode_data)
  505. {
  506. StringBuilder builder;
  507. SourceGenerator generator { builder };
  508. generator.set("casing_transform_size", String::number(unicode_data.largest_casing_transform_size));
  509. auto generate_enum = [&](StringView name, StringView default_, Vector<String> values, Vector<Alias> aliases = {}) {
  510. quick_sort(values);
  511. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  512. generator.set("name", name);
  513. generator.set("underlying", String::formatted("{}UnderlyingType", name));
  514. generator.set("type", ((values.size() + !default_.is_empty()) < 256) ? "u8"sv : "u16"sv);
  515. generator.append(R"~~~(
  516. using @underlying@ = @type@;
  517. enum class @name@ : @underlying@ {)~~~");
  518. if (!default_.is_empty()) {
  519. generator.set("default", default_);
  520. generator.append(R"~~~(
  521. @default@,)~~~");
  522. }
  523. for (auto const& value : values) {
  524. generator.set("value", value);
  525. generator.append(R"~~~(
  526. @value@,)~~~");
  527. }
  528. for (auto const& alias : aliases) {
  529. generator.set("alias", alias.alias);
  530. generator.set("value", alias.name);
  531. generator.append(R"~~~(
  532. @alias@ = @value@,)~~~");
  533. }
  534. generator.append(R"~~~(
  535. };
  536. )~~~");
  537. };
  538. generator.append(R"~~~(
  539. #pragma once
  540. #include <AK/Types.h>
  541. #include <LibUnicode/Forward.h>
  542. #include <LibUnicode/UnicodeLocale.h>
  543. namespace Unicode {
  544. )~~~");
  545. generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
  546. generate_enum("GeneralCategory"sv, {}, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  547. generate_enum("Property"sv, {}, unicode_data.prop_list.keys(), unicode_data.prop_aliases);
  548. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), unicode_data.script_aliases);
  549. generate_enum("Block"sv, {}, unicode_data.block_list.keys(), unicode_data.block_aliases);
  550. generate_enum("GraphemeBreakProperty"sv, {}, unicode_data.grapheme_break_props.keys());
  551. generate_enum("WordBreakProperty"sv, {}, unicode_data.word_break_props.keys());
  552. generate_enum("SentenceBreakProperty"sv, {}, unicode_data.sentence_break_props.keys());
  553. generator.append(R"~~~(
  554. struct SpecialCasing {
  555. u32 code_point { 0 };
  556. u32 lowercase_mapping[@casing_transform_size@];
  557. u32 lowercase_mapping_size { 0 };
  558. u32 uppercase_mapping[@casing_transform_size@];
  559. u32 uppercase_mapping_size { 0 };
  560. u32 titlecase_mapping[@casing_transform_size@];
  561. u32 titlecase_mapping_size { 0 };
  562. Locale locale { Locale::None };
  563. Condition condition { Condition::None };
  564. };
  565. }
  566. )~~~");
  567. TRY(file.write(generator.as_string_view().bytes()));
  568. return {};
  569. }
  570. static ErrorOr<void> generate_unicode_data_implementation(Core::Stream::BufferedFile& file, UnicodeData const& unicode_data)
  571. {
  572. StringBuilder builder;
  573. SourceGenerator generator { builder };
  574. generator.set("string_index_type"sv, s_string_index_type);
  575. generator.set("largest_special_casing_size", String::number(unicode_data.largest_special_casing_size));
  576. generator.set("special_casing_size", String::number(unicode_data.special_casing.size()));
  577. generator.append(R"~~~(
  578. #include <AK/Array.h>
  579. #include <AK/BinarySearch.h>
  580. #include <AK/CharacterTypes.h>
  581. #include <AK/Optional.h>
  582. #include <AK/Span.h>
  583. #include <AK/String.h>
  584. #include <AK/StringView.h>
  585. #include <LibUnicode/CharacterTypes.h>
  586. #include <LibUnicode/UnicodeData.h>
  587. namespace Unicode {
  588. )~~~");
  589. unicode_data.unique_strings.generate(generator);
  590. auto append_list_and_size = [&](auto const& list, StringView format) {
  591. if (list.is_empty()) {
  592. generator.append(", {}, 0");
  593. return;
  594. }
  595. bool first = true;
  596. generator.append(", {");
  597. for (auto const& item : list) {
  598. generator.append(first ? " "sv : ", "sv);
  599. generator.append(String::formatted(format, item));
  600. first = false;
  601. }
  602. generator.append(String::formatted(" }}, {}", list.size()));
  603. };
  604. generator.append(R"~~~(
  605. static constexpr Array<SpecialCasing, @special_casing_size@> s_special_casing { {)~~~");
  606. for (auto const& casing : unicode_data.special_casing) {
  607. generator.set("code_point", String::formatted("{:#x}", casing.code_point));
  608. generator.append(R"~~~(
  609. { @code_point@)~~~");
  610. constexpr auto format = "0x{:x}"sv;
  611. append_list_and_size(casing.lowercase_mapping, format);
  612. append_list_and_size(casing.uppercase_mapping, format);
  613. append_list_and_size(casing.titlecase_mapping, format);
  614. generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
  615. generator.append(", Locale::@locale@");
  616. generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
  617. generator.append(", Condition::@condition@");
  618. generator.append(" },");
  619. }
  620. generator.append(R"~~~(
  621. } };
  622. struct CodePointMapping {
  623. u32 code_point { 0 };
  624. u32 mapping { 0 };
  625. };
  626. struct SpecialCaseMapping {
  627. u32 code_point { 0 };
  628. Array<SpecialCasing const*, @largest_special_casing_size@> special_casing {};
  629. u32 special_casing_size { 0 };
  630. };
  631. struct CodePointAbbreviation {
  632. u32 code_point { 0 };
  633. @string_index_type@ abbreviation { 0 };
  634. };
  635. template<typename MappingType>
  636. struct CodePointComparator {
  637. constexpr int operator()(u32 code_point, MappingType const& mapping)
  638. {
  639. return code_point - mapping.code_point;
  640. }
  641. };
  642. struct CodePointRangeComparator {
  643. constexpr int operator()(u32 code_point, CodePointRange const& range)
  644. {
  645. return (code_point > range.last) - (code_point < range.first);
  646. }
  647. };
  648. struct BlockNameData {
  649. CodePointRange code_point_range {};
  650. @string_index_type@ display_name { 0 };
  651. };
  652. struct BlockNameComparator : public CodePointRangeComparator {
  653. constexpr int operator()(u32 code_point, BlockNameData const& name)
  654. {
  655. return CodePointRangeComparator::operator()(code_point, name.code_point_range);
  656. }
  657. };
  658. struct CodePointName {
  659. CodePointRange code_point_range {};
  660. @string_index_type@ display_name { 0 };
  661. };
  662. struct CodePointNameComparator : public CodePointRangeComparator {
  663. constexpr int operator()(u32 code_point, CodePointName const& name)
  664. {
  665. return CodePointRangeComparator::operator()(code_point, name.code_point_range);
  666. }
  667. };
  668. )~~~");
  669. auto append_code_point_mappings = [&](StringView name, StringView mapping_type, u32 size, auto mapping_getter) {
  670. generator.set("name", name);
  671. generator.set("mapping_type", mapping_type);
  672. generator.set("size", String::number(size));
  673. generator.append(R"~~~(
  674. static constexpr Array<@mapping_type@, @size@> s_@name@_mappings { {
  675. )~~~");
  676. constexpr size_t max_mappings_per_row = 20;
  677. size_t mappings_in_current_row = 0;
  678. for (auto const& data : unicode_data.code_point_data) {
  679. auto mapping = mapping_getter(data);
  680. if constexpr (requires { mapping.has_value(); }) {
  681. if (!mapping.has_value())
  682. continue;
  683. } else {
  684. if (mapping.is_empty())
  685. continue;
  686. }
  687. if (mappings_in_current_row++ > 0)
  688. generator.append(" ");
  689. generator.set("code_point", String::formatted("{:#x}", data.code_point));
  690. generator.append("{ @code_point@");
  691. if constexpr (IsSame<decltype(mapping), Optional<u32>> || IsSame<decltype(mapping), Optional<StringIndexType>>) {
  692. generator.set("mapping", String::formatted("{:#x}", *mapping));
  693. generator.append(", @mapping@ },");
  694. } else {
  695. append_list_and_size(data.special_casing_indices, "&s_special_casing[{}]"sv);
  696. generator.append(" },");
  697. }
  698. if (mappings_in_current_row == max_mappings_per_row) {
  699. mappings_in_current_row = 0;
  700. generator.append("\n ");
  701. }
  702. }
  703. generator.append(R"~~~(
  704. } };
  705. )~~~");
  706. };
  707. append_code_point_mappings("combining_class"sv, "CodePointMapping"sv, unicode_data.code_points_with_non_zero_combining_class,
  708. [](auto const& data) -> Optional<u32> {
  709. if (data.canonical_combining_class == 0)
  710. return {};
  711. return data.canonical_combining_class;
  712. });
  713. append_code_point_mappings("uppercase"sv, "CodePointMapping"sv, unicode_data.simple_uppercase_mapping_size, [](auto const& data) { return data.simple_uppercase_mapping; });
  714. append_code_point_mappings("lowercase"sv, "CodePointMapping"sv, unicode_data.simple_lowercase_mapping_size, [](auto const& data) { return data.simple_lowercase_mapping; });
  715. append_code_point_mappings("special_case"sv, "SpecialCaseMapping"sv, unicode_data.code_points_with_special_casing, [](auto const& data) { return data.special_casing_indices; });
  716. append_code_point_mappings("abbreviation"sv, "CodePointAbbreviation"sv, unicode_data.code_point_abbreviations.size(), [](auto const& data) { return data.abbreviation; });
  717. auto append_code_point_range_list = [&](String name, Vector<CodePointRange> const& ranges) {
  718. generator.set("name", name);
  719. generator.set("size", String::number(ranges.size()));
  720. generator.append(R"~~~(
  721. static constexpr Array<CodePointRange, @size@> @name@ { {
  722. )~~~");
  723. constexpr size_t max_ranges_per_row = 20;
  724. size_t ranges_in_current_row = 0;
  725. for (auto const& range : ranges) {
  726. if (ranges_in_current_row++ > 0)
  727. generator.append(" ");
  728. generator.set("first", String::formatted("{:#x}", range.first));
  729. generator.set("last", String::formatted("{:#x}", range.last));
  730. generator.append("{ @first@, @last@ },");
  731. if (ranges_in_current_row == max_ranges_per_row) {
  732. ranges_in_current_row = 0;
  733. generator.append("\n ");
  734. }
  735. }
  736. generator.append(R"~~~(
  737. } };
  738. )~~~");
  739. };
  740. auto append_prop_list = [&](StringView collection_name, StringView property_format, PropList const& property_list) {
  741. for (auto const& property : property_list) {
  742. auto name = String::formatted(property_format, property.key);
  743. append_code_point_range_list(move(name), property.value);
  744. }
  745. auto property_names = property_list.keys();
  746. quick_sort(property_names);
  747. generator.set("name", collection_name);
  748. generator.set("size", String::number(property_names.size()));
  749. generator.append(R"~~~(
  750. static constexpr Array<Span<CodePointRange const>, @size@> @name@ { {)~~~");
  751. for (auto const& property_name : property_names) {
  752. generator.set("name", String::formatted(property_format, property_name));
  753. generator.append(R"~~~(
  754. @name@.span(),)~~~");
  755. }
  756. generator.append(R"~~~(
  757. } };
  758. )~~~");
  759. };
  760. append_prop_list("s_general_categories"sv, "s_general_category_{}"sv, unicode_data.general_categories);
  761. append_prop_list("s_properties"sv, "s_property_{}"sv, unicode_data.prop_list);
  762. append_prop_list("s_scripts"sv, "s_script_{}"sv, unicode_data.script_list);
  763. append_prop_list("s_script_extensions"sv, "s_script_extension_{}"sv, unicode_data.script_extensions);
  764. append_prop_list("s_blocks"sv, "s_block_{}"sv, unicode_data.block_list);
  765. append_prop_list("s_grapheme_break_properties"sv, "s_grapheme_break_property_{}"sv, unicode_data.grapheme_break_props);
  766. append_prop_list("s_word_break_properties"sv, "s_word_break_property_{}"sv, unicode_data.word_break_props);
  767. append_prop_list("s_sentence_break_properties"sv, "s_sentence_break_property_{}"sv, unicode_data.sentence_break_props);
  768. auto append_code_point_display_names = [&](StringView type, StringView name, auto const& display_names) {
  769. constexpr size_t max_values_per_row = 30;
  770. size_t values_in_current_row = 0;
  771. generator.set("type", type);
  772. generator.set("name", name);
  773. generator.set("size", String::number(display_names.size()));
  774. generator.append(R"~~~(
  775. static constexpr Array<@type@, @size@> @name@ { {
  776. )~~~");
  777. for (auto const& display_name : display_names) {
  778. if (values_in_current_row++ > 0)
  779. generator.append(", ");
  780. generator.set("first", String::formatted("{:#x}", display_name.code_point_range.first));
  781. generator.set("last", String::formatted("{:#x}", display_name.code_point_range.last));
  782. generator.set("name", String::number(display_name.name));
  783. generator.append("{ { @first@, @last@ }, @name@ }");
  784. if (values_in_current_row == max_values_per_row) {
  785. values_in_current_row = 0;
  786. generator.append(",\n ");
  787. }
  788. }
  789. generator.append(R"~~~(
  790. } };
  791. )~~~");
  792. };
  793. append_code_point_display_names("BlockNameData"sv, "s_block_display_names"sv, unicode_data.block_display_names);
  794. append_code_point_display_names("CodePointName"sv, "s_code_point_display_names"sv, unicode_data.code_point_display_names);
  795. generator.append(R"~~~(
  796. Optional<StringView> code_point_block_display_name(u32 code_point)
  797. {
  798. if (auto const* entry = binary_search(s_block_display_names, code_point, nullptr, BlockNameComparator {}))
  799. return decode_string(entry->display_name);
  800. return {};
  801. }
  802. Span<BlockName const> block_display_names()
  803. {
  804. static auto display_names = []() {
  805. Array<BlockName, s_block_display_names.size()> display_names;
  806. for (size_t i = 0; i < s_block_display_names.size(); ++i) {
  807. auto const& display_name = s_block_display_names[i];
  808. display_names[i] = { display_name.code_point_range, decode_string(display_name.display_name) };
  809. }
  810. return display_names;
  811. }();
  812. return display_names.span();
  813. }
  814. Optional<String> code_point_display_name(u32 code_point)
  815. {
  816. if (auto const* entry = binary_search(s_code_point_display_names, code_point, nullptr, CodePointNameComparator {})) {
  817. auto display_name = decode_string(entry->display_name);
  818. if (display_name.ends_with("{:X}"sv))
  819. return String::formatted(display_name, code_point);
  820. return display_name;
  821. }
  822. return {};
  823. }
  824. )~~~");
  825. auto append_code_point_mapping_search = [&](StringView method, StringView mappings, StringView fallback) {
  826. generator.set("method", method);
  827. generator.set("mappings", mappings);
  828. generator.set("fallback", fallback);
  829. generator.append(R"~~~(
  830. u32 @method@(u32 code_point)
  831. {
  832. auto const* mapping = binary_search(@mappings@, code_point, nullptr, CodePointComparator<CodePointMapping> {});
  833. return mapping ? mapping->mapping : @fallback@;
  834. }
  835. )~~~");
  836. };
  837. append_code_point_mapping_search("canonical_combining_class"sv, "s_combining_class_mappings"sv, "0"sv);
  838. append_code_point_mapping_search("to_unicode_uppercase"sv, "s_uppercase_mappings"sv, "code_point"sv);
  839. append_code_point_mapping_search("to_unicode_lowercase"sv, "s_lowercase_mappings"sv, "code_point"sv);
  840. generator.append(R"~~~(
  841. Span<SpecialCasing const* const> special_case_mapping(u32 code_point)
  842. {
  843. auto const* mapping = binary_search(s_special_case_mappings, code_point, nullptr, CodePointComparator<SpecialCaseMapping> {});
  844. if (mapping == nullptr)
  845. return {};
  846. return mapping->special_casing.span().slice(0, mapping->special_casing_size);
  847. }
  848. Optional<StringView> code_point_abbreviation(u32 code_point)
  849. {
  850. auto const* mapping = binary_search(s_abbreviation_mappings, code_point, nullptr, CodePointComparator<CodePointAbbreviation> {});
  851. if (mapping == nullptr)
  852. return {};
  853. if (mapping->abbreviation == 0)
  854. return {};
  855. return decode_string(mapping->abbreviation);
  856. }
  857. )~~~");
  858. auto append_prop_search = [&](StringView enum_title, StringView enum_snake, StringView collection_name) {
  859. generator.set("enum_title", enum_title);
  860. generator.set("enum_snake", enum_snake);
  861. generator.set("collection_name", collection_name);
  862. generator.append(R"~~~(
  863. bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@)
  864. {
  865. auto index = static_cast<@enum_title@UnderlyingType>(@enum_snake@);
  866. auto const& ranges = @collection_name@.at(index);
  867. auto const* range = binary_search(ranges, code_point, nullptr, CodePointRangeComparator {});
  868. return range != nullptr;
  869. }
  870. )~~~");
  871. };
  872. auto append_from_string = [&](StringView enum_title, StringView enum_snake, PropList const& prop_list, Vector<Alias> const& aliases) {
  873. HashValueMap<StringView> hashes;
  874. hashes.ensure_capacity(prop_list.size() + aliases.size());
  875. for (auto const& prop : prop_list)
  876. hashes.set(prop.key.hash(), prop.key);
  877. for (auto const& alias : aliases)
  878. hashes.set(alias.alias.hash(), alias.alias);
  879. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  880. };
  881. append_prop_search("GeneralCategory"sv, "general_category"sv, "s_general_categories"sv);
  882. append_from_string("GeneralCategory"sv, "general_category"sv, unicode_data.general_categories, unicode_data.general_category_aliases);
  883. append_prop_search("Property"sv, "property"sv, "s_properties"sv);
  884. append_from_string("Property"sv, "property"sv, unicode_data.prop_list, unicode_data.prop_aliases);
  885. append_prop_search("Script"sv, "script"sv, "s_scripts"sv);
  886. append_prop_search("Script"sv, "script_extension"sv, "s_script_extensions"sv);
  887. append_from_string("Script"sv, "script"sv, unicode_data.script_list, unicode_data.script_aliases);
  888. append_prop_search("Block"sv, "block"sv, "s_blocks"sv);
  889. append_from_string("Block"sv, "block"sv, unicode_data.block_list, unicode_data.block_aliases);
  890. append_prop_search("GraphemeBreakProperty"sv, "grapheme_break_property"sv, "s_grapheme_break_properties"sv);
  891. append_prop_search("WordBreakProperty"sv, "word_break_property"sv, "s_word_break_properties"sv);
  892. append_prop_search("SentenceBreakProperty"sv, "sentence_break_property"sv, "s_sentence_break_properties"sv);
  893. generator.append(R"~~~(
  894. }
  895. )~~~");
  896. TRY(file.write(generator.as_string_view().bytes()));
  897. return {};
  898. }
  899. static Vector<u32> flatten_code_point_ranges(Vector<CodePointRange> const& code_points)
  900. {
  901. Vector<u32> flattened;
  902. for (auto const& range : code_points) {
  903. flattened.grow_capacity(range.last - range.first);
  904. for (u32 code_point = range.first; code_point <= range.last; ++code_point)
  905. flattened.append(code_point);
  906. }
  907. return flattened;
  908. }
  909. static Vector<CodePointRange> form_code_point_ranges(Vector<u32> code_points)
  910. {
  911. Vector<CodePointRange> ranges;
  912. u32 range_start = code_points[0];
  913. u32 range_end = range_start;
  914. for (size_t i = 1; i < code_points.size(); ++i) {
  915. u32 code_point = code_points[i];
  916. if ((code_point - range_end) == 1) {
  917. range_end = code_point;
  918. } else {
  919. ranges.append({ range_start, range_end });
  920. range_start = code_point;
  921. range_end = code_point;
  922. }
  923. }
  924. ranges.append({ range_start, range_end });
  925. return ranges;
  926. }
  927. static void sort_and_merge_code_point_ranges(Vector<CodePointRange>& code_points)
  928. {
  929. quick_sort(code_points, [](auto const& range1, auto const& range2) {
  930. return range1.first < range2.first;
  931. });
  932. for (size_t i = 0; i < code_points.size() - 1;) {
  933. if (code_points[i].last >= code_points[i + 1].first) {
  934. code_points[i].last = max(code_points[i].last, code_points[i + 1].last);
  935. code_points.remove(i + 1);
  936. } else {
  937. ++i;
  938. }
  939. }
  940. auto all_code_points = flatten_code_point_ranges(code_points);
  941. code_points = form_code_point_ranges(all_code_points);
  942. }
  943. static void populate_general_category_unions(PropList& general_categories)
  944. {
  945. // The Unicode standard defines General Category values which are not in any UCD file. These
  946. // values are simply unions of other values.
  947. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  948. auto populate_union = [&](auto alias, auto categories) {
  949. auto& code_points = general_categories.ensure(alias);
  950. for (auto const& category : categories)
  951. code_points.extend(general_categories.find(category)->value);
  952. sort_and_merge_code_point_ranges(code_points);
  953. };
  954. populate_union("LC"sv, Array { "Ll"sv, "Lu"sv, "Lt"sv });
  955. populate_union("L"sv, Array { "Lu"sv, "Ll"sv, "Lt"sv, "Lm"sv, "Lo"sv });
  956. populate_union("M"sv, Array { "Mn"sv, "Mc"sv, "Me"sv });
  957. populate_union("N"sv, Array { "Nd"sv, "Nl"sv, "No"sv });
  958. populate_union("P"sv, Array { "Pc"sv, "Pd"sv, "Ps"sv, "Pe"sv, "Pi"sv, "Pf"sv, "Po"sv });
  959. populate_union("S"sv, Array { "Sm"sv, "Sc"sv, "Sk"sv, "So"sv });
  960. populate_union("Z"sv, Array { "Zs"sv, "Zl"sv, "Zp"sv });
  961. populate_union("C"sv, Array { "Cc"sv, "Cf"sv, "Cs"sv, "Co"sv, "Cn"sv });
  962. }
  963. static void normalize_script_extensions(PropList& script_extensions, PropList const& script_list, Vector<Alias> const& script_aliases)
  964. {
  965. // The ScriptExtensions UCD file lays out its code point ranges rather uniquely compared to
  966. // other files. The Script listed on each line may either be a full Script string or an aliased
  967. // abbreviation. Further, the extensions may or may not include the base Script list. Normalize
  968. // the extensions here to be keyed by the full Script name and always include the base list.
  969. auto extensions = move(script_extensions);
  970. script_extensions = script_list;
  971. for (auto const& extension : extensions) {
  972. auto it = find_if(script_aliases.begin(), script_aliases.end(), [&](auto const& alias) { return extension.key == alias.alias; });
  973. auto const& key = (it == script_aliases.end()) ? extension.key : it->name;
  974. auto& code_points = script_extensions.find(key)->value;
  975. code_points.extend(extension.value);
  976. sort_and_merge_code_point_ranges(code_points);
  977. }
  978. // Lastly, the Common and Inherited script extensions are special. They must not contain any
  979. // code points which appear in other script extensions. The ScriptExtensions UCD file does not
  980. // list these extensions, therefore this peculiarity must be handled programmatically.
  981. // https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values
  982. auto code_point_has_other_extension = [&](StringView key, u32 code_point) {
  983. for (auto const& extension : extensions) {
  984. if (extension.key == key)
  985. continue;
  986. if (any_of(extension.value, [&](auto const& r) { return (r.first <= code_point) && (code_point <= r.last); }))
  987. return true;
  988. }
  989. return false;
  990. };
  991. auto get_code_points_without_other_extensions = [&](StringView key) {
  992. auto code_points = flatten_code_point_ranges(script_list.find(key)->value);
  993. code_points.remove_all_matching([&](u32 c) { return code_point_has_other_extension(key, c); });
  994. return code_points;
  995. };
  996. auto common_code_points = get_code_points_without_other_extensions("Common"sv);
  997. script_extensions.set("Common"sv, form_code_point_ranges(common_code_points));
  998. auto inherited_code_points = get_code_points_without_other_extensions("Inherited"sv);
  999. script_extensions.set("Inherited"sv, form_code_point_ranges(inherited_code_points));
  1000. }
  1001. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1002. {
  1003. StringView generated_header_path;
  1004. StringView generated_implementation_path;
  1005. StringView unicode_data_path;
  1006. StringView special_casing_path;
  1007. StringView derived_general_category_path;
  1008. StringView prop_list_path;
  1009. StringView derived_core_prop_path;
  1010. StringView derived_binary_prop_path;
  1011. StringView prop_alias_path;
  1012. StringView prop_value_alias_path;
  1013. StringView name_alias_path;
  1014. StringView scripts_path;
  1015. StringView script_extensions_path;
  1016. StringView blocks_path;
  1017. StringView emoji_data_path;
  1018. StringView normalization_path;
  1019. StringView grapheme_break_path;
  1020. StringView word_break_path;
  1021. StringView sentence_break_path;
  1022. Core::ArgsParser args_parser;
  1023. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  1024. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  1025. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  1026. args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
  1027. args_parser.add_option(derived_general_category_path, "Path to DerivedGeneralCategory.txt file", "derived-general-category-path", 'g', "derived-general-category-path");
  1028. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  1029. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  1030. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  1031. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  1032. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  1033. args_parser.add_option(name_alias_path, "Path to NameAliases.txt file", "name-alias-path", 'm', "name-alias-path");
  1034. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  1035. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  1036. args_parser.add_option(blocks_path, "Path to Blocks.txt file", "blocks-path", 'k', "blocks-path");
  1037. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  1038. args_parser.add_option(normalization_path, "Path to DerivedNormalizationProps.txt file", "normalization-path", 'n', "normalization-path");
  1039. args_parser.add_option(grapheme_break_path, "Path to GraphemeBreakProperty.txt file", "grapheme-break-path", 'f', "grapheme-break-path");
  1040. args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path");
  1041. args_parser.add_option(sentence_break_path, "Path to SentenceBreakProperty.txt file", "sentence-break-path", 'i', "sentence-break-path");
  1042. args_parser.parse(arguments);
  1043. auto generated_header_file = TRY(open_file(generated_header_path, Core::Stream::OpenMode::Write));
  1044. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::Stream::OpenMode::Write));
  1045. auto unicode_data_file = TRY(open_file(unicode_data_path, Core::Stream::OpenMode::Read));
  1046. auto derived_general_category_file = TRY(open_file(derived_general_category_path, Core::Stream::OpenMode::Read));
  1047. auto special_casing_file = TRY(open_file(special_casing_path, Core::Stream::OpenMode::Read));
  1048. auto prop_list_file = TRY(open_file(prop_list_path, Core::Stream::OpenMode::Read));
  1049. auto derived_core_prop_file = TRY(open_file(derived_core_prop_path, Core::Stream::OpenMode::Read));
  1050. auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path, Core::Stream::OpenMode::Read));
  1051. auto prop_alias_file = TRY(open_file(prop_alias_path, Core::Stream::OpenMode::Read));
  1052. auto prop_value_alias_file = TRY(open_file(prop_value_alias_path, Core::Stream::OpenMode::Read));
  1053. auto name_alias_file = TRY(open_file(name_alias_path, Core::Stream::OpenMode::Read));
  1054. auto scripts_file = TRY(open_file(scripts_path, Core::Stream::OpenMode::Read));
  1055. auto script_extensions_file = TRY(open_file(script_extensions_path, Core::Stream::OpenMode::Read));
  1056. auto blocks_file = TRY(open_file(blocks_path, Core::Stream::OpenMode::Read));
  1057. auto emoji_data_file = TRY(open_file(emoji_data_path, Core::Stream::OpenMode::Read));
  1058. auto normalization_file = TRY(open_file(normalization_path, Core::Stream::OpenMode::Read));
  1059. auto grapheme_break_file = TRY(open_file(grapheme_break_path, Core::Stream::OpenMode::Read));
  1060. auto word_break_file = TRY(open_file(word_break_path, Core::Stream::OpenMode::Read));
  1061. auto sentence_break_file = TRY(open_file(sentence_break_path, Core::Stream::OpenMode::Read));
  1062. UnicodeData unicode_data {};
  1063. TRY(parse_special_casing(*special_casing_file, unicode_data));
  1064. TRY(parse_prop_list(*derived_general_category_file, unicode_data.general_categories));
  1065. TRY(parse_prop_list(*prop_list_file, unicode_data.prop_list));
  1066. TRY(parse_prop_list(*derived_core_prop_file, unicode_data.prop_list));
  1067. TRY(parse_prop_list(*derived_binary_prop_file, unicode_data.prop_list));
  1068. TRY(parse_prop_list(*emoji_data_file, unicode_data.prop_list));
  1069. TRY(parse_normalization_props(*normalization_file, unicode_data));
  1070. TRY(parse_alias_list(*prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases));
  1071. TRY(parse_prop_list(*scripts_file, unicode_data.script_list));
  1072. TRY(parse_prop_list(*script_extensions_file, unicode_data.script_extensions, true));
  1073. TRY(parse_block_display_names(*blocks_file, unicode_data));
  1074. TRY(parse_prop_list(*blocks_file, unicode_data.block_list, false, true));
  1075. TRY(parse_name_aliases(*name_alias_file, unicode_data));
  1076. TRY(parse_prop_list(*grapheme_break_file, unicode_data.grapheme_break_props));
  1077. TRY(parse_prop_list(*word_break_file, unicode_data.word_break_props));
  1078. TRY(parse_prop_list(*sentence_break_file, unicode_data.sentence_break_props));
  1079. populate_general_category_unions(unicode_data.general_categories);
  1080. TRY(parse_unicode_data(*unicode_data_file, unicode_data));
  1081. TRY(parse_value_alias_list(*prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases));
  1082. TRY(parse_value_alias_list(*prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false));
  1083. TRY(parse_value_alias_list(*prop_value_alias_file, "blk"sv, unicode_data.block_list.keys(), unicode_data.block_aliases, false, true));
  1084. normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases);
  1085. TRY(generate_unicode_data_header(*generated_header_file, unicode_data));
  1086. TRY(generate_unicode_data_implementation(*generated_implementation_file, unicode_data));
  1087. return 0;
  1088. }