GenerateUnicodeData.cpp 53 KB

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