GenerateUnicodeData.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  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/ByteString.h>
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/Error.h>
  12. #include <AK/Find.h>
  13. #include <AK/HashMap.h>
  14. #include <AK/Optional.h>
  15. #include <AK/QuickSort.h>
  16. #include <AK/SourceGenerator.h>
  17. #include <AK/StringUtils.h>
  18. #include <AK/Types.h>
  19. #include <AK/Vector.h>
  20. #include <LibCore/ArgsParser.h>
  21. #include <LibUnicode/CharacterTypes.h>
  22. // https://www.unicode.org/reports/tr44/#SpecialCasing.txt
  23. struct SpecialCasing {
  24. u32 index { 0 };
  25. u32 code_point { 0 };
  26. Vector<u32> lowercase_mapping;
  27. Vector<u32> uppercase_mapping;
  28. Vector<u32> titlecase_mapping;
  29. ByteString locale;
  30. ByteString condition;
  31. };
  32. // https://www.unicode.org/reports/tr44/#CaseFolding.txt
  33. struct CaseFolding {
  34. u32 code_point { 0 };
  35. StringView status { "Common"sv };
  36. Vector<u32> mapping { 0 };
  37. };
  38. // https://www.unicode.org/reports/tr44/#PropList.txt
  39. using PropList = HashMap<ByteString, Vector<Unicode::CodePointRange>>;
  40. // https://www.unicode.org/reports/tr44/#DerivedNormalizationProps.txt
  41. enum class QuickCheck {
  42. Yes,
  43. No,
  44. Maybe,
  45. };
  46. struct Normalization {
  47. Unicode::CodePointRange code_point_range;
  48. Vector<u32> value;
  49. QuickCheck quick_check { QuickCheck::Yes };
  50. };
  51. using NormalizationProps = HashMap<ByteString, Vector<Normalization>>;
  52. struct CasingTable {
  53. bool operator==(CasingTable const& other) const
  54. {
  55. return canonical_combining_class == other.canonical_combining_class
  56. && simple_lowercase_mapping == other.simple_lowercase_mapping
  57. && simple_uppercase_mapping == other.simple_uppercase_mapping
  58. && simple_titlecase_mapping == other.simple_titlecase_mapping
  59. && special_casing_indices == other.special_casing_indices
  60. && case_folding_indices == other.case_folding_indices;
  61. }
  62. u8 canonical_combining_class { 0 };
  63. Optional<u32> simple_uppercase_mapping;
  64. Optional<u32> simple_lowercase_mapping;
  65. Optional<u32> simple_titlecase_mapping;
  66. Vector<u32> special_casing_indices;
  67. Vector<u32> case_folding_indices;
  68. };
  69. // https://www.unicode.org/reports/tr44/#UnicodeData.txt
  70. struct CodePointData {
  71. u32 code_point { 0 };
  72. ByteString name;
  73. ByteString bidi_class;
  74. Optional<i8> numeric_value_decimal;
  75. Optional<i8> numeric_value_digit;
  76. Optional<i8> numeric_value_numeric;
  77. bool bidi_mirrored { false };
  78. ByteString unicode_1_name;
  79. ByteString iso_comment;
  80. CasingTable casing;
  81. };
  82. using PropertyTable = Vector<bool>;
  83. static constexpr auto CODE_POINT_TABLES_MSB_COUNT = 16u;
  84. static_assert(CODE_POINT_TABLES_MSB_COUNT < 24u);
  85. static constexpr auto CODE_POINT_TABLES_LSB_COUNT = 24u - CODE_POINT_TABLES_MSB_COUNT;
  86. static constexpr auto CODE_POINT_TABLES_LSB_MASK = NumericLimits<u32>::max() >> (NumericLimits<u32>::digits() - CODE_POINT_TABLES_LSB_COUNT);
  87. template<typename PropertyType>
  88. struct CodePointTables {
  89. Vector<size_t> stage1;
  90. Vector<size_t> stage2;
  91. Vector<PropertyType> unique_properties;
  92. };
  93. struct CodePointBidiClass {
  94. Unicode::CodePointRange code_point_range;
  95. ByteString bidi_class;
  96. };
  97. struct UnicodeData {
  98. Vector<SpecialCasing> special_casing;
  99. u32 largest_special_casing_mapping_size { 0 };
  100. Vector<ByteString> conditions;
  101. Vector<ByteString> locales;
  102. Vector<CaseFolding> case_folding;
  103. u32 largest_case_folding_mapping_size { 0 };
  104. Vector<StringView> statuses;
  105. Vector<CodePointData> code_point_data;
  106. // https://www.unicode.org/reports/tr44/#General_Category_Values
  107. PropList general_categories;
  108. Vector<Alias> general_category_aliases;
  109. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  110. // any UCD file. Assigned code point ranges are derived as this generator is executed.
  111. // https://unicode.org/reports/tr18/#General_Category_Property
  112. PropList prop_list {
  113. { "Any"sv, { { 0, 0x10ffff } } },
  114. { "Assigned"sv, {} },
  115. { "ASCII"sv, { { 0, 0x7f } } },
  116. };
  117. Vector<Alias> prop_aliases;
  118. PropList script_list {
  119. { "Unknown"sv, {} },
  120. };
  121. Vector<Alias> script_aliases;
  122. PropList script_extensions;
  123. // FIXME: We are not yet doing anything with this data. It will be needed for String.prototype.normalize.
  124. NormalizationProps normalization_props;
  125. PropList grapheme_break_props;
  126. PropList word_break_props;
  127. PropList sentence_break_props;
  128. CodePointTables<CasingTable> casing_tables;
  129. CodePointTables<PropertyTable> general_category_tables;
  130. CodePointTables<PropertyTable> property_tables;
  131. CodePointTables<PropertyTable> script_tables;
  132. CodePointTables<PropertyTable> script_extension_tables;
  133. CodePointTables<PropertyTable> grapheme_break_tables;
  134. CodePointTables<PropertyTable> word_break_tables;
  135. CodePointTables<PropertyTable> sentence_break_tables;
  136. HashTable<ByteString> bidirectional_classes;
  137. Vector<CodePointBidiClass> code_point_bidirectional_classes;
  138. };
  139. static ByteString sanitize_entry(ByteString const& entry)
  140. {
  141. auto sanitized = entry.replace("-"sv, "_"sv, ReplaceMode::All);
  142. sanitized = sanitized.replace(" "sv, "_"sv, ReplaceMode::All);
  143. StringBuilder builder;
  144. bool next_is_upper = true;
  145. for (auto ch : sanitized) {
  146. if (next_is_upper)
  147. builder.append_code_point(to_ascii_uppercase(ch));
  148. else
  149. builder.append_code_point(ch);
  150. next_is_upper = ch == '_';
  151. }
  152. return builder.to_byte_string();
  153. }
  154. static ErrorOr<void> parse_special_casing(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  155. {
  156. Array<u8, 1024> buffer;
  157. while (TRY(file.can_read_line())) {
  158. auto line = TRY(file.read_line(buffer));
  159. if (line.is_empty() || line.starts_with('#'))
  160. continue;
  161. if (auto index = line.find('#'); index.has_value())
  162. line = line.substring_view(0, *index);
  163. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  164. VERIFY(segments.size() == 5 || segments.size() == 6);
  165. SpecialCasing casing {};
  166. casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  167. casing.lowercase_mapping = parse_code_point_list(segments[1]);
  168. casing.titlecase_mapping = parse_code_point_list(segments[2]);
  169. casing.uppercase_mapping = parse_code_point_list(segments[3]);
  170. if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
  171. auto conditions = condition.split_view(' ', SplitBehavior::KeepEmpty);
  172. VERIFY(conditions.size() == 1 || conditions.size() == 2);
  173. if (conditions.size() == 2) {
  174. casing.locale = conditions[0];
  175. casing.condition = conditions[1];
  176. } else if (all_of(conditions[0], is_ascii_lower_alpha)) {
  177. casing.locale = conditions[0];
  178. } else {
  179. casing.condition = conditions[0];
  180. }
  181. if (!casing.locale.is_empty()) {
  182. casing.locale = ByteString::formatted("{:c}{}", to_ascii_uppercase(casing.locale[0]), casing.locale.substring_view(1));
  183. if (!unicode_data.locales.contains_slow(casing.locale))
  184. unicode_data.locales.append(casing.locale);
  185. }
  186. casing.condition = casing.condition.replace("_"sv, ""sv, ReplaceMode::All);
  187. if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
  188. unicode_data.conditions.append(casing.condition);
  189. }
  190. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.lowercase_mapping.size());
  191. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.titlecase_mapping.size());
  192. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.uppercase_mapping.size());
  193. unicode_data.special_casing.append(move(casing));
  194. }
  195. quick_sort(unicode_data.special_casing, [](auto const& lhs, auto const& rhs) {
  196. if (lhs.code_point != rhs.code_point)
  197. return lhs.code_point < rhs.code_point;
  198. if (lhs.locale.is_empty() && !rhs.locale.is_empty())
  199. return false;
  200. if (!lhs.locale.is_empty() && rhs.locale.is_empty())
  201. return true;
  202. return lhs.locale < rhs.locale;
  203. });
  204. for (u32 i = 0; i < unicode_data.special_casing.size(); ++i)
  205. unicode_data.special_casing[i].index = i;
  206. return {};
  207. }
  208. static ErrorOr<void> parse_case_folding(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  209. {
  210. Array<u8, 1024> buffer;
  211. while (TRY(file.can_read_line())) {
  212. auto line = TRY(file.read_line(buffer));
  213. if (line.is_empty() || line.starts_with('#'))
  214. continue;
  215. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  216. VERIFY(segments.size() == 4);
  217. CaseFolding folding {};
  218. folding.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  219. folding.mapping = parse_code_point_list(segments[2]);
  220. switch (segments[1].trim_whitespace()[0]) {
  221. case 'C':
  222. folding.status = "Common"sv;
  223. break;
  224. case 'F':
  225. folding.status = "Full"sv;
  226. break;
  227. case 'S':
  228. folding.status = "Simple"sv;
  229. break;
  230. case 'T':
  231. folding.status = "Special"sv;
  232. break;
  233. }
  234. unicode_data.largest_case_folding_mapping_size = max(unicode_data.largest_case_folding_mapping_size, folding.mapping.size());
  235. if (!unicode_data.statuses.contains_slow(folding.status))
  236. unicode_data.statuses.append(folding.status);
  237. unicode_data.case_folding.append(move(folding));
  238. }
  239. quick_sort(unicode_data.case_folding, [](auto const& lhs, auto const& rhs) {
  240. if (lhs.code_point != rhs.code_point)
  241. return lhs.code_point < rhs.code_point;
  242. return lhs.status < rhs.status;
  243. });
  244. return {};
  245. }
  246. static ErrorOr<void> parse_prop_list(Core::InputBufferedFile& file, PropList& prop_list, bool multi_value_property = false, bool sanitize_property = false)
  247. {
  248. Array<u8, 1024> buffer;
  249. while (TRY(file.can_read_line())) {
  250. auto line = TRY(file.read_line(buffer));
  251. if (line.is_empty() || line.starts_with('#'))
  252. continue;
  253. if (auto index = line.find('#'); index.has_value())
  254. line = line.substring_view(0, *index);
  255. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  256. VERIFY(segments.size() == 2 || segments.size() == 3);
  257. String combined_segment_buffer;
  258. if (segments.size() == 3) {
  259. // For example, in DerivedCoreProperties.txt, there are lines such as:
  260. //
  261. // 094D ; InCB; Linker # Mn DEVANAGARI SIGN VIRAMA
  262. //
  263. // These are used in text segmentation to prevent breaking within some extended grapheme clusters.
  264. // So here, we combine the segments into a single property, which allows us to simply do code point
  265. // property lookups at runtime for specific Indic Conjunct Break sequences.
  266. combined_segment_buffer = MUST(String::join('_', Array { segments[1].trim_whitespace(), segments[2].trim_whitespace() }));
  267. segments[1] = combined_segment_buffer;
  268. }
  269. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  270. Vector<StringView> properties;
  271. if (multi_value_property)
  272. properties = segments[1].trim_whitespace().split_view(' ');
  273. else
  274. properties = { segments[1].trim_whitespace() };
  275. for (auto& property : properties) {
  276. auto& code_points = prop_list.ensure(sanitize_property ? sanitize_entry(property).trim_whitespace() : ByteString { property.trim_whitespace() });
  277. code_points.append(code_point_range);
  278. }
  279. }
  280. return {};
  281. }
  282. static ErrorOr<void> parse_alias_list(Core::InputBufferedFile& file, PropList const& prop_list, Vector<Alias>& prop_aliases)
  283. {
  284. ByteString current_property;
  285. Array<u8, 1024> buffer;
  286. auto append_alias = [&](auto alias, auto property) {
  287. // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip.
  288. if (alias == property)
  289. return;
  290. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  291. if (!prop_list.contains(property))
  292. return;
  293. prop_aliases.append({ property, alias });
  294. };
  295. while (TRY(file.can_read_line())) {
  296. auto line = TRY(file.read_line(buffer));
  297. if (line.is_empty() || line.starts_with('#')) {
  298. if (line.ends_with("Properties"sv))
  299. current_property = line.substring_view(2);
  300. continue;
  301. }
  302. // Note: For now, we only care about Binary Property aliases for Unicode property escapes.
  303. if (current_property != "Binary Properties"sv)
  304. continue;
  305. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  306. VERIFY((segments.size() == 2) || (segments.size() == 3));
  307. auto alias = segments[0].trim_whitespace();
  308. auto property = segments[1].trim_whitespace();
  309. append_alias(alias, property);
  310. if (segments.size() == 3) {
  311. alias = segments[2].trim_whitespace();
  312. append_alias(alias, property);
  313. }
  314. }
  315. return {};
  316. }
  317. static ErrorOr<void> parse_value_alias_list(Core::InputBufferedFile& file, StringView desired_category, Vector<ByteString> const& value_list, Vector<Alias>& prop_aliases, bool primary_value_is_first = true, bool sanitize_alias = false)
  318. {
  319. TRY(file.seek(0, SeekMode::SetPosition));
  320. Array<u8, 1024> buffer;
  321. auto append_alias = [&](auto alias, auto value) {
  322. // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip.
  323. if (alias == value)
  324. return;
  325. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  326. if (!value_list.contains_slow(value))
  327. return;
  328. prop_aliases.append({ value, alias });
  329. };
  330. while (TRY(file.can_read_line())) {
  331. auto line = TRY(file.read_line(buffer));
  332. if (line.is_empty() || line.starts_with('#'))
  333. continue;
  334. if (auto index = line.find('#'); index.has_value())
  335. line = line.substring_view(0, *index);
  336. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  337. auto category = segments[0].trim_whitespace();
  338. if (category != desired_category)
  339. continue;
  340. VERIFY((segments.size() == 3) || (segments.size() == 4));
  341. auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace();
  342. auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace();
  343. append_alias(sanitize_alias ? sanitize_entry(alias) : ByteString { alias }, value);
  344. if (segments.size() == 4) {
  345. alias = segments[3].trim_whitespace();
  346. append_alias(sanitize_alias ? sanitize_entry(alias) : ByteString { alias }, value);
  347. }
  348. }
  349. return {};
  350. }
  351. static ErrorOr<void> parse_normalization_props(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  352. {
  353. Array<u8, 1024> buffer;
  354. while (TRY(file.can_read_line())) {
  355. auto line = TRY(file.read_line(buffer));
  356. if (line.is_empty() || line.starts_with('#'))
  357. continue;
  358. if (auto index = line.find('#'); index.has_value())
  359. line = line.substring_view(0, *index);
  360. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  361. VERIFY((segments.size() == 2) || (segments.size() == 3));
  362. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  363. auto property = segments[1].trim_whitespace().to_byte_string();
  364. Vector<u32> value;
  365. QuickCheck quick_check = QuickCheck::Yes;
  366. if (segments.size() == 3) {
  367. auto value_or_quick_check = segments[2].trim_whitespace();
  368. if ((value_or_quick_check == "N"sv))
  369. quick_check = QuickCheck::No;
  370. else if ((value_or_quick_check == "M"sv))
  371. quick_check = QuickCheck::Maybe;
  372. else
  373. value = parse_code_point_list(value_or_quick_check);
  374. }
  375. auto& normalizations = unicode_data.normalization_props.ensure(property);
  376. normalizations.append({ code_point_range, move(value), quick_check });
  377. auto& prop_list = unicode_data.prop_list.ensure(property);
  378. prop_list.append(move(code_point_range));
  379. }
  380. return {};
  381. }
  382. static ErrorOr<void> parse_unicode_data(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  383. {
  384. Optional<u32> code_point_range_start;
  385. auto& assigned_code_points = unicode_data.prop_list.find("Assigned"sv)->value;
  386. Optional<u32> assigned_code_point_range_start = 0;
  387. u32 previous_code_point = 0;
  388. Array<u8, 1024> buffer;
  389. while (TRY(file.can_read_line())) {
  390. auto line = TRY(file.read_line(buffer));
  391. if (line.is_empty())
  392. continue;
  393. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  394. VERIFY(segments.size() == 15);
  395. CodePointData data {};
  396. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  397. data.name = segments[1];
  398. data.casing.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
  399. data.bidi_class = segments[4];
  400. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  401. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  402. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  403. data.bidi_mirrored = segments[9] == "Y"sv;
  404. data.unicode_1_name = segments[10];
  405. data.iso_comment = segments[11];
  406. data.casing.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
  407. data.casing.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
  408. data.casing.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
  409. if (!assigned_code_point_range_start.has_value())
  410. assigned_code_point_range_start = data.code_point;
  411. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>"sv)) {
  412. VERIFY(!code_point_range_start.has_value() && assigned_code_point_range_start.has_value());
  413. code_point_range_start = data.code_point;
  414. data.name = data.name.substring(1, data.name.length() - 9);
  415. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  416. assigned_code_point_range_start.clear();
  417. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>"sv)) {
  418. VERIFY(code_point_range_start.has_value());
  419. Unicode::CodePointRange code_point_range { *code_point_range_start, data.code_point };
  420. assigned_code_points.append(code_point_range);
  421. data.name = data.name.substring(1, data.name.length() - 8);
  422. code_point_range_start.clear();
  423. unicode_data.code_point_bidirectional_classes.append({ code_point_range, data.bidi_class });
  424. } else {
  425. unicode_data.code_point_bidirectional_classes.append({ { data.code_point, data.code_point }, data.bidi_class });
  426. if ((data.code_point > 0) && (data.code_point - previous_code_point) != 1) {
  427. VERIFY(assigned_code_point_range_start.has_value());
  428. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  429. assigned_code_point_range_start = data.code_point;
  430. }
  431. }
  432. for (auto const& casing : unicode_data.special_casing) {
  433. if (casing.code_point == data.code_point)
  434. data.casing.special_casing_indices.append(casing.index);
  435. }
  436. for (size_t i = 0; i < unicode_data.case_folding.size(); ++i) {
  437. if (auto const& folding = unicode_data.case_folding[i]; folding.code_point == data.code_point)
  438. data.casing.case_folding_indices.append(i);
  439. }
  440. unicode_data.bidirectional_classes.set(data.bidi_class, AK::HashSetExistingEntryBehavior::Keep);
  441. previous_code_point = data.code_point;
  442. unicode_data.code_point_data.append(move(data));
  443. }
  444. return {};
  445. }
  446. static ErrorOr<void> generate_unicode_data_header(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  447. {
  448. StringBuilder builder;
  449. SourceGenerator generator { builder };
  450. generator.set("special_casing_mapping_size", ByteString::number(unicode_data.largest_special_casing_mapping_size));
  451. generator.set("case_folding_mapping_size", ByteString::number(unicode_data.largest_case_folding_mapping_size));
  452. auto generate_enum = [&](StringView name, StringView default_, auto values, Vector<Alias> aliases = {}) {
  453. quick_sort(values);
  454. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  455. generator.set("name", name);
  456. generator.set("underlying", ByteString::formatted("{}UnderlyingType", name));
  457. generator.set("type", ((values.size() + !default_.is_empty()) < 256) ? "u8"sv : "u16"sv);
  458. generator.append(R"~~~(
  459. using @underlying@ = @type@;
  460. enum class @name@ : @underlying@ {)~~~");
  461. if (!default_.is_empty()) {
  462. generator.set("default", default_);
  463. generator.append(R"~~~(
  464. @default@,)~~~");
  465. }
  466. for (auto const& value : values) {
  467. generator.set("value", value);
  468. generator.append(R"~~~(
  469. @value@,)~~~");
  470. }
  471. for (auto const& alias : aliases) {
  472. generator.set("alias", alias.alias);
  473. generator.set("value", alias.name);
  474. generator.append(R"~~~(
  475. @alias@ = @value@,)~~~");
  476. }
  477. generator.append(R"~~~(
  478. };
  479. )~~~");
  480. };
  481. generator.append(R"~~~(
  482. #pragma once
  483. #include <AK/Types.h>
  484. #include <LibUnicode/Forward.h>
  485. namespace Unicode {
  486. )~~~");
  487. generate_enum("Locale"sv, "None"sv, unicode_data.locales);
  488. generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
  489. generate_enum("CaseFoldingStatus"sv, {}, move(unicode_data.statuses));
  490. generate_enum("GeneralCategory"sv, {}, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  491. generate_enum("Property"sv, {}, unicode_data.prop_list.keys(), unicode_data.prop_aliases);
  492. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), unicode_data.script_aliases);
  493. generate_enum("GraphemeBreakProperty"sv, {}, unicode_data.grapheme_break_props.keys());
  494. generate_enum("WordBreakProperty"sv, {}, unicode_data.word_break_props.keys());
  495. generate_enum("SentenceBreakProperty"sv, {}, unicode_data.sentence_break_props.keys());
  496. generate_enum("BidirectionalClass"sv, {}, unicode_data.bidirectional_classes.values());
  497. generator.append(R"~~~(
  498. struct SpecialCasing {
  499. u32 code_point { 0 };
  500. u32 lowercase_mapping[@special_casing_mapping_size@];
  501. u32 lowercase_mapping_size { 0 };
  502. u32 uppercase_mapping[@special_casing_mapping_size@];
  503. u32 uppercase_mapping_size { 0 };
  504. u32 titlecase_mapping[@special_casing_mapping_size@];
  505. u32 titlecase_mapping_size { 0 };
  506. Locale locale { Locale::None };
  507. Condition condition { Condition::None };
  508. };
  509. struct CaseFolding {
  510. u32 code_point { 0 };
  511. CaseFoldingStatus status { CaseFoldingStatus::Common };
  512. u32 mapping[@case_folding_mapping_size@];
  513. u32 mapping_size { 0 };
  514. };
  515. Optional<Locale> locale_from_string(StringView locale);
  516. ReadonlySpan<SpecialCasing> special_case_mapping(u32 code_point);
  517. ReadonlySpan<CaseFolding> case_folding_mapping(u32 code_point);
  518. }
  519. )~~~");
  520. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  521. return {};
  522. }
  523. static ErrorOr<void> generate_unicode_data_implementation(Core::InputBufferedFile& file, UnicodeData const& unicode_data)
  524. {
  525. StringBuilder builder;
  526. SourceGenerator generator { builder };
  527. generator.set("special_casing_size", ByteString::number(unicode_data.special_casing.size()));
  528. generator.set("case_folding_size", ByteString::number(unicode_data.case_folding.size()));
  529. generator.set("CODE_POINT_TABLES_LSB_COUNT", TRY(String::number(CODE_POINT_TABLES_LSB_COUNT)));
  530. generator.set("CODE_POINT_TABLES_LSB_MASK", TRY(String::formatted("{:#x}", CODE_POINT_TABLES_LSB_MASK)));
  531. generator.append(R"~~~(
  532. #include <AK/Array.h>
  533. #include <AK/BinarySearch.h>
  534. #include <AK/CharacterTypes.h>
  535. #include <AK/Optional.h>
  536. #include <AK/Span.h>
  537. #include <AK/ByteString.h>
  538. #include <AK/StringView.h>
  539. #include <LibUnicode/CharacterTypes.h>
  540. #include <LibUnicode/UnicodeData.h>
  541. #include <LibUnicode/Normalize.h>
  542. namespace Unicode {
  543. )~~~");
  544. auto append_list_and_size = [&](auto const& list, StringView format) {
  545. if (list.is_empty()) {
  546. generator.append(", {}, 0");
  547. return;
  548. }
  549. bool first = true;
  550. generator.append(", {");
  551. for (auto const& item : list) {
  552. generator.append(first ? " "sv : ", "sv);
  553. generator.append(ByteString::formatted(format, item));
  554. first = false;
  555. }
  556. generator.append(ByteString::formatted(" }}, {}", list.size()));
  557. };
  558. generator.append(R"~~~(
  559. static constexpr Array<SpecialCasing, @special_casing_size@> s_special_case { {)~~~");
  560. for (auto const& casing : unicode_data.special_casing) {
  561. generator.set("code_point", ByteString::formatted("{:#x}", casing.code_point));
  562. generator.append(R"~~~(
  563. { @code_point@)~~~");
  564. constexpr auto format = "{:#x}"sv;
  565. append_list_and_size(casing.lowercase_mapping, format);
  566. append_list_and_size(casing.uppercase_mapping, format);
  567. append_list_and_size(casing.titlecase_mapping, format);
  568. generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
  569. generator.append(", Locale::@locale@");
  570. generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
  571. generator.append(", Condition::@condition@");
  572. generator.append(" },");
  573. }
  574. generator.append(R"~~~(
  575. } };
  576. static constexpr Array<CaseFolding, @case_folding_size@> s_case_folding { {)~~~");
  577. for (auto const& folding : unicode_data.case_folding) {
  578. generator.set("code_point", ByteString::formatted("{:#x}", folding.code_point));
  579. generator.set("status", folding.status);
  580. generator.append(R"~~~(
  581. { @code_point@, CaseFoldingStatus::@status@)~~~");
  582. append_list_and_size(folding.mapping, "{:#x}"sv);
  583. generator.append(" },");
  584. }
  585. generator.append(R"~~~(
  586. } };
  587. struct CasingTable {
  588. u8 canonical_combining_class { 0 };
  589. i32 simple_uppercase_mapping { -1 };
  590. i32 simple_lowercase_mapping { -1 };
  591. i32 simple_titlecase_mapping { -1 };
  592. u32 special_casing_start_index { 0 };
  593. u32 special_casing_size { 0 };
  594. u32 case_folding_start_index { 0 };
  595. u32 case_folding_size { 0 };
  596. };
  597. template<typename MappingType>
  598. struct CodePointComparator {
  599. constexpr int operator()(u32 code_point, MappingType const& mapping)
  600. {
  601. return code_point - mapping.code_point;
  602. }
  603. };
  604. struct BidiClassData {
  605. CodePointRange code_point_range {};
  606. BidirectionalClass bidi_class {};
  607. };
  608. struct CodePointBidiClassComparator : public CodePointRangeComparator {
  609. constexpr int operator()(u32 code_point, BidiClassData const& bidi_class)
  610. {
  611. return CodePointRangeComparator::operator()(code_point, bidi_class.code_point_range);
  612. }
  613. };
  614. )~~~");
  615. auto append_casing_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  616. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  617. generator.set("size", TRY(String::number(unique_properties.size())));
  618. auto optional_code_point_to_string = [](auto const& code_point) -> ErrorOr<String> {
  619. if (!code_point.has_value())
  620. return "-1"_string;
  621. return String::number(*code_point);
  622. };
  623. auto first_index_to_string = [](auto const& list) -> ErrorOr<String> {
  624. if (list.is_empty())
  625. return "0"_string;
  626. return String::number(list.first());
  627. };
  628. generator.append(R"~~~(
  629. static constexpr Array<CasingTable, @size@> @name@ { {)~~~");
  630. for (auto const& casing : unique_properties) {
  631. generator.set("canonical_combining_class", TRY(String::number(casing.canonical_combining_class)));
  632. generator.set("simple_uppercase_mapping", TRY(optional_code_point_to_string(casing.simple_uppercase_mapping)));
  633. generator.set("simple_lowercase_mapping", TRY(optional_code_point_to_string(casing.simple_lowercase_mapping)));
  634. generator.set("simple_titlecase_mapping", TRY(optional_code_point_to_string(casing.simple_titlecase_mapping)));
  635. generator.set("special_casing_start_index", TRY(first_index_to_string(casing.special_casing_indices)));
  636. generator.set("special_casing_size", TRY(String::number(casing.special_casing_indices.size())));
  637. generator.set("case_folding_start_index", TRY(first_index_to_string(casing.case_folding_indices)));
  638. generator.set("case_folding_size", TRY(String::number(casing.case_folding_indices.size())));
  639. generator.append(R"~~~(
  640. { @canonical_combining_class@, @simple_uppercase_mapping@, @simple_lowercase_mapping@, @simple_titlecase_mapping@, @special_casing_start_index@, @special_casing_size@, @case_folding_start_index@, @case_folding_size@ },)~~~");
  641. }
  642. generator.append(R"~~~(
  643. } };
  644. )~~~");
  645. return {};
  646. };
  647. auto append_property_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  648. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  649. generator.set("outer_size", TRY(String::number(unique_properties.size())));
  650. generator.set("inner_size", TRY(String::number(unique_properties[0].size())));
  651. generator.append(R"~~~(
  652. static constexpr Array<Array<bool, @inner_size@>, @outer_size@> @name@ { {)~~~");
  653. for (auto const& property_set : unique_properties) {
  654. generator.append(R"~~~(
  655. { )~~~");
  656. for (auto value : property_set) {
  657. generator.set("value", TRY(String::formatted("{}", value)));
  658. generator.append("@value@, ");
  659. }
  660. generator.append(" },");
  661. }
  662. generator.append(R"~~~(
  663. } };
  664. )~~~");
  665. return {};
  666. };
  667. auto append_code_point_tables = [&](StringView collection_snake, auto const& tables, auto& append_unique_properties) -> ErrorOr<void> {
  668. auto append_stage = [&](auto const& stage, auto name, auto type) -> ErrorOr<void> {
  669. generator.set("name", TRY(String::formatted("{}_{}", collection_snake, name)));
  670. generator.set("size", TRY(String::number(stage.size())));
  671. generator.set("type", type);
  672. generator.append(R"~~~(
  673. static constexpr Array<@type@, @size@> @name@ { {
  674. )~~~");
  675. static constexpr size_t max_values_per_row = 300;
  676. size_t values_in_current_row = 0;
  677. for (auto value : stage) {
  678. if (values_in_current_row++ > 0)
  679. generator.append(", ");
  680. generator.set("value", TRY(String::number(value)));
  681. generator.append("@value@");
  682. if (values_in_current_row == max_values_per_row) {
  683. values_in_current_row = 0;
  684. generator.append(",\n ");
  685. }
  686. }
  687. generator.append(R"~~~(
  688. } };
  689. )~~~");
  690. return {};
  691. };
  692. TRY(append_stage(tables.stage1, "stage1"sv, "u16"sv));
  693. TRY(append_stage(tables.stage2, "stage2"sv, "u16"sv));
  694. TRY(append_unique_properties(collection_snake, tables.unique_properties));
  695. return {};
  696. };
  697. TRY(append_code_point_tables("s_casings"sv, unicode_data.casing_tables, append_casing_table));
  698. TRY(append_code_point_tables("s_general_categories"sv, unicode_data.general_category_tables, append_property_table));
  699. TRY(append_code_point_tables("s_properties"sv, unicode_data.property_tables, append_property_table));
  700. TRY(append_code_point_tables("s_scripts"sv, unicode_data.script_tables, append_property_table));
  701. TRY(append_code_point_tables("s_script_extensions"sv, unicode_data.script_extension_tables, append_property_table));
  702. TRY(append_code_point_tables("s_grapheme_break_properties"sv, unicode_data.grapheme_break_tables, append_property_table));
  703. TRY(append_code_point_tables("s_word_break_properties"sv, unicode_data.word_break_tables, append_property_table));
  704. TRY(append_code_point_tables("s_sentence_break_properties"sv, unicode_data.sentence_break_tables, append_property_table));
  705. {
  706. constexpr size_t max_bidi_classes_per_row = 20;
  707. size_t bidi_classes_in_current_row = 0;
  708. generator.set("size"sv, ByteString::number(unicode_data.code_point_bidirectional_classes.size()));
  709. generator.append(R"~~~(
  710. static constexpr Array<BidiClassData, @size@> s_bidirectional_classes { {
  711. )~~~");
  712. for (auto const& data : unicode_data.code_point_bidirectional_classes) {
  713. if (bidi_classes_in_current_row++ > 0)
  714. generator.append(", ");
  715. generator.set("first", ByteString::formatted("{:#x}", data.code_point_range.first));
  716. generator.set("last", ByteString::formatted("{:#x}", data.code_point_range.last));
  717. generator.set("bidi_class", data.bidi_class);
  718. generator.append("{ { @first@, @last@ }, BidirectionalClass::@bidi_class@ }");
  719. if (bidi_classes_in_current_row == max_bidi_classes_per_row) {
  720. bidi_classes_in_current_row = 0;
  721. generator.append(",\n ");
  722. }
  723. }
  724. generator.append(R"~~~(
  725. } };
  726. )~~~");
  727. }
  728. generator.append(R"~~~(
  729. static CasingTable const& casing_table_for_code_point(u32 code_point)
  730. {
  731. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  732. auto stage2_index = s_casings_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  733. auto unique_properties_index = s_casings_stage2[stage2_index];
  734. return s_casings_unique_properties[unique_properties_index];
  735. }
  736. )~~~");
  737. auto append_code_point_mapping_search = [&](StringView method, StringView mapping, Optional<StringView> const& fallback = {}) {
  738. generator.set("method", method);
  739. generator.set("mapping", mapping);
  740. generator.append(R"~~~(
  741. u32 @method@(u32 code_point)
  742. {
  743. auto const& casing_table = casing_table_for_code_point(code_point);
  744. auto mapping = casing_table.@mapping@;
  745. )~~~");
  746. if (fallback.has_value()) {
  747. generator.set("fallback", *fallback);
  748. generator.append(R"~~~(
  749. return mapping == -1 ? @fallback@ : static_cast<u32>(mapping);)~~~");
  750. } else {
  751. generator.append(R"~~~(
  752. return mapping;)~~~");
  753. }
  754. generator.append(R"~~~(
  755. }
  756. )~~~");
  757. };
  758. append_code_point_mapping_search("canonical_combining_class"sv, "canonical_combining_class"sv);
  759. append_code_point_mapping_search("to_unicode_uppercase"sv, "simple_uppercase_mapping"sv, "code_point"sv);
  760. append_code_point_mapping_search("to_unicode_lowercase"sv, "simple_lowercase_mapping"sv, "code_point"sv);
  761. append_code_point_mapping_search("to_unicode_titlecase"sv, "simple_titlecase_mapping"sv, "code_point"sv);
  762. generator.append(R"~~~(
  763. ReadonlySpan<SpecialCasing> special_case_mapping(u32 code_point)
  764. {
  765. auto const& casing_table = casing_table_for_code_point(code_point);
  766. if (casing_table.special_casing_size == 0)
  767. return {};
  768. return s_special_case.span().slice(casing_table.special_casing_start_index, casing_table.special_casing_size);
  769. }
  770. ReadonlySpan<CaseFolding> case_folding_mapping(u32 code_point)
  771. {
  772. auto const& casing_table = casing_table_for_code_point(code_point);
  773. if (casing_table.case_folding_size == 0)
  774. return {};
  775. return s_case_folding.span().slice(casing_table.case_folding_start_index, casing_table.case_folding_size);
  776. }
  777. Optional<BidirectionalClass> bidirectional_class(u32 code_point)
  778. {
  779. if (auto const* entry = binary_search(s_bidirectional_classes, code_point, nullptr, CodePointBidiClassComparator {}))
  780. return entry->bidi_class;
  781. return {};
  782. }
  783. )~~~");
  784. auto append_prop_search = [&](StringView enum_title, StringView enum_snake, StringView collection_name) -> ErrorOr<void> {
  785. generator.set("enum_title", enum_title);
  786. generator.set("enum_snake", enum_snake);
  787. generator.set("collection_name", collection_name);
  788. generator.append(R"~~~(
  789. bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@)
  790. {
  791. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  792. auto stage2_index = @collection_name@_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  793. auto unique_properties_index = @collection_name@_stage2[stage2_index];
  794. auto const& property_set = @collection_name@_unique_properties[unique_properties_index];
  795. return property_set[to_underlying(@enum_snake@)];
  796. }
  797. )~~~");
  798. return {};
  799. };
  800. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& prop_list, Vector<Alias> const& aliases) -> ErrorOr<void> {
  801. HashValueMap<StringView> hashes;
  802. TRY(hashes.try_ensure_capacity(prop_list.size() + aliases.size()));
  803. ValueFromStringOptions options {};
  804. for (auto const& prop : prop_list) {
  805. if constexpr (IsSame<RemoveCVReference<decltype(prop)>, ByteString>) {
  806. hashes.set(CaseInsensitiveASCIIStringViewTraits::hash(prop), prop);
  807. options.sensitivity = CaseSensitivity::CaseInsensitive;
  808. } else {
  809. hashes.set(prop.key.hash(), prop.key);
  810. }
  811. }
  812. for (auto const& alias : aliases)
  813. hashes.set(alias.alias.hash(), alias.alias);
  814. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes), options);
  815. return {};
  816. };
  817. TRY(append_from_string("Locale"sv, "locale"sv, unicode_data.locales, {}));
  818. TRY(append_prop_search("GeneralCategory"sv, "general_category"sv, "s_general_categories"sv));
  819. TRY(append_from_string("GeneralCategory"sv, "general_category"sv, unicode_data.general_categories, unicode_data.general_category_aliases));
  820. TRY(append_prop_search("Property"sv, "property"sv, "s_properties"sv));
  821. TRY(append_from_string("Property"sv, "property"sv, unicode_data.prop_list, unicode_data.prop_aliases));
  822. TRY(append_prop_search("Script"sv, "script"sv, "s_scripts"sv));
  823. TRY(append_prop_search("Script"sv, "script_extension"sv, "s_script_extensions"sv));
  824. TRY(append_from_string("Script"sv, "script"sv, unicode_data.script_list, unicode_data.script_aliases));
  825. TRY(append_prop_search("GraphemeBreakProperty"sv, "grapheme_break_property"sv, "s_grapheme_break_properties"sv));
  826. TRY(append_prop_search("WordBreakProperty"sv, "word_break_property"sv, "s_word_break_properties"sv));
  827. TRY(append_prop_search("SentenceBreakProperty"sv, "sentence_break_property"sv, "s_sentence_break_properties"sv));
  828. TRY(append_from_string("BidirectionalClass"sv, "bidirectional_class"sv, unicode_data.bidirectional_classes, {}));
  829. generator.append(R"~~~(
  830. }
  831. )~~~");
  832. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  833. return {};
  834. }
  835. static Vector<u32> flatten_code_point_ranges(Vector<Unicode::CodePointRange> const& code_points)
  836. {
  837. Vector<u32> flattened;
  838. for (auto const& range : code_points) {
  839. flattened.grow_capacity(range.last - range.first);
  840. for (u32 code_point = range.first; code_point <= range.last; ++code_point)
  841. flattened.append(code_point);
  842. }
  843. return flattened;
  844. }
  845. static Vector<Unicode::CodePointRange> form_code_point_ranges(Vector<u32> code_points)
  846. {
  847. Vector<Unicode::CodePointRange> ranges;
  848. u32 range_start = code_points[0];
  849. u32 range_end = range_start;
  850. for (size_t i = 1; i < code_points.size(); ++i) {
  851. u32 code_point = code_points[i];
  852. if ((code_point - range_end) == 1) {
  853. range_end = code_point;
  854. } else {
  855. ranges.append({ range_start, range_end });
  856. range_start = code_point;
  857. range_end = code_point;
  858. }
  859. }
  860. ranges.append({ range_start, range_end });
  861. return ranges;
  862. }
  863. static void sort_and_merge_code_point_ranges(Vector<Unicode::CodePointRange>& code_points)
  864. {
  865. quick_sort(code_points, [](auto const& range1, auto const& range2) {
  866. return range1.first < range2.first;
  867. });
  868. for (size_t i = 0; i < code_points.size() - 1;) {
  869. if (code_points[i].last >= code_points[i + 1].first) {
  870. code_points[i].last = max(code_points[i].last, code_points[i + 1].last);
  871. code_points.remove(i + 1);
  872. } else {
  873. ++i;
  874. }
  875. }
  876. auto all_code_points = flatten_code_point_ranges(code_points);
  877. code_points = form_code_point_ranges(all_code_points);
  878. }
  879. static void populate_general_category_unions(PropList& general_categories)
  880. {
  881. // The Unicode standard defines General Category values which are not in any UCD file. These
  882. // values are simply unions of other values.
  883. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  884. auto populate_union = [&](auto alias, auto categories) {
  885. auto& code_points = general_categories.ensure(alias);
  886. for (auto const& category : categories)
  887. code_points.extend(general_categories.find(category)->value);
  888. sort_and_merge_code_point_ranges(code_points);
  889. };
  890. populate_union("LC"sv, Array { "Ll"sv, "Lu"sv, "Lt"sv });
  891. populate_union("L"sv, Array { "Lu"sv, "Ll"sv, "Lt"sv, "Lm"sv, "Lo"sv });
  892. populate_union("M"sv, Array { "Mn"sv, "Mc"sv, "Me"sv });
  893. populate_union("N"sv, Array { "Nd"sv, "Nl"sv, "No"sv });
  894. populate_union("P"sv, Array { "Pc"sv, "Pd"sv, "Ps"sv, "Pe"sv, "Pi"sv, "Pf"sv, "Po"sv });
  895. populate_union("S"sv, Array { "Sm"sv, "Sc"sv, "Sk"sv, "So"sv });
  896. populate_union("Z"sv, Array { "Zs"sv, "Zl"sv, "Zp"sv });
  897. populate_union("C"sv, Array { "Cc"sv, "Cf"sv, "Cs"sv, "Co"sv, "Cn"sv });
  898. }
  899. static ErrorOr<void> normalize_script_extensions(PropList& script_extensions, PropList const& script_list, Vector<Alias> const& script_aliases)
  900. {
  901. // The ScriptExtensions UCD file lays out its code point ranges rather uniquely compared to
  902. // other files. The Script listed on each line may either be a full Script string or an aliased
  903. // abbreviation. Further, the extensions may or may not include the base Script list. Normalize
  904. // the extensions here to be keyed by the full Script name and always include the base list.
  905. auto extensions = move(script_extensions);
  906. script_extensions = TRY(script_list.clone());
  907. for (auto const& extension : extensions) {
  908. auto it = find_if(script_aliases.begin(), script_aliases.end(), [&](auto const& alias) { return extension.key == alias.alias; });
  909. auto const& key = (it == script_aliases.end()) ? extension.key : it->name;
  910. auto& code_points = script_extensions.find(key)->value;
  911. code_points.extend(extension.value);
  912. sort_and_merge_code_point_ranges(code_points);
  913. }
  914. // Lastly, the Common and Inherited script extensions are special. They must not contain any
  915. // code points which appear in other script extensions. The ScriptExtensions UCD file does not
  916. // list these extensions, therefore this peculiarity must be handled programmatically.
  917. // https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values
  918. auto code_point_has_other_extension = [&](StringView key, u32 code_point) {
  919. for (auto const& extension : extensions) {
  920. if (extension.key == key)
  921. continue;
  922. if (any_of(extension.value, [&](auto const& r) { return (r.first <= code_point) && (code_point <= r.last); }))
  923. return true;
  924. }
  925. return false;
  926. };
  927. auto get_code_points_without_other_extensions = [&](StringView key) {
  928. auto code_points = flatten_code_point_ranges(script_list.find(key)->value);
  929. code_points.remove_all_matching([&](u32 c) { return code_point_has_other_extension(key, c); });
  930. return code_points;
  931. };
  932. auto common_code_points = get_code_points_without_other_extensions("Common"sv);
  933. script_extensions.set("Common"sv, form_code_point_ranges(common_code_points));
  934. auto inherited_code_points = get_code_points_without_other_extensions("Inherited"sv);
  935. script_extensions.set("Inherited"sv, form_code_point_ranges(inherited_code_points));
  936. return {};
  937. }
  938. struct CasingMetadata {
  939. using ConstIterator = typename Vector<CodePointData>::ConstIterator;
  940. CasingMetadata(Vector<CodePointData> const& code_point_data)
  941. : iterator(code_point_data.begin())
  942. , end(code_point_data.end())
  943. {
  944. }
  945. ConstIterator iterator;
  946. ConstIterator const end;
  947. Vector<size_t> current_block;
  948. HashMap<decltype(current_block), size_t> unique_blocks;
  949. };
  950. struct PropertyMetadata {
  951. static ErrorOr<PropertyMetadata> create(PropList& property_list)
  952. {
  953. PropertyMetadata data;
  954. TRY(data.property_values.try_ensure_capacity(property_list.size()));
  955. TRY(data.property_set.try_ensure_capacity(property_list.size()));
  956. auto property_names = property_list.keys();
  957. quick_sort(property_names);
  958. for (auto& property_name : property_names) {
  959. auto& code_point_ranges = property_list.get(property_name).value();
  960. data.property_values.unchecked_append(move(code_point_ranges));
  961. }
  962. return data;
  963. }
  964. Vector<typename PropList::ValueType> property_values;
  965. PropertyTable property_set;
  966. Vector<size_t> current_block;
  967. HashMap<decltype(current_block), size_t> unique_blocks;
  968. };
  969. // The goal here is to produce a set of tables that represent a category of code point properties for every code point.
  970. // The most naive method would be to generate a single table per category, each with one entry per code point. Each of
  971. // those tables would have a size of 0x10ffff though, which is a non-starter. Instead, we create a set of 2-stage lookup
  972. // tables per category.
  973. //
  974. // To do so, it's important to note that Unicode tends to organize code points with similar properties together. This
  975. // leads to long series of code points with identical properties. Therefore, if we divide the 0x10ffff code points into
  976. // fixed-size blocks, many of those blocks will also be identical.
  977. //
  978. // So we iterate over every code point, classifying each one for the category of interest. We represent a classification
  979. // as a list of booleans. We store the classification in the CodePointTables::unique_properties list for this category.
  980. // As the name implies, this list is de-duplicated; we store the index into this list in a separate list, which we call
  981. // a "block".
  982. //
  983. // As we iterate, we "pause" every BLOCK_SIZE code points to examine the block. If the block is unique so far, we extend
  984. // CodePointTables::stage2 with the entries of that block (so CodePointTables::stage2 is also a list of indices into
  985. // CodePointTables::unique_properties). We then append the index of the start of that block in CodePointTables::stage2
  986. // to CodePointTables::stage1.
  987. //
  988. // The value of BLOCK_SIZE is determined by CodePointTables::MSB_COUNT and CodePointTables::LSB_COUNT. We need 24 bits
  989. // to describe all code points; the blocks we create are based on splitting these bits into 2 segments. We currently use
  990. // a 16:8 bit split. So when perform a runtime lookup of a code point in the 2-stage tables, we:
  991. //
  992. // 1. Use most-significant 16 bits of the code point as the index into CodePointTables::stage1. That value is the
  993. // index into CodePointTables::stage2 of the start of the block that contains properties for this code point.
  994. //
  995. // 2. Add the least-significant 8 bits of the code point to that value, to use as the index into
  996. // CodePointTables::stage2. As described above, that value is the index into CodePointTables::unique_properties,
  997. // which contains the classification for this code point.
  998. //
  999. // Using the code point GeneralCategory as an example, we end up with a CodePointTables::stage1 with a size of ~4000,
  1000. // a CodePointTables::stage2 with a size of ~40,000, and a CodePointTables::unique_properties with a size of ~30. So
  1001. // this process reduces over 1 million entries (0x10ffff) to ~44,030.
  1002. //
  1003. // For much more in-depth reading, see: https://icu.unicode.org/design/struct/utrie
  1004. static constexpr auto MAX_CODE_POINT = 0x10ffffu;
  1005. template<typename T>
  1006. static ErrorOr<void> update_tables(u32 code_point, CodePointTables<T>& tables, auto& metadata, auto const& values)
  1007. {
  1008. static constexpr auto BLOCK_SIZE = CODE_POINT_TABLES_LSB_MASK + 1;
  1009. size_t unique_properties_index = 0;
  1010. if (auto block_index = tables.unique_properties.find_first_index(values); block_index.has_value()) {
  1011. unique_properties_index = *block_index;
  1012. } else {
  1013. unique_properties_index = tables.unique_properties.size();
  1014. TRY(tables.unique_properties.try_append(values));
  1015. }
  1016. TRY(metadata.current_block.try_append(unique_properties_index));
  1017. if (metadata.current_block.size() == BLOCK_SIZE || code_point == MAX_CODE_POINT) {
  1018. size_t stage2_index = 0;
  1019. if (auto block_index = metadata.unique_blocks.get(metadata.current_block); block_index.has_value()) {
  1020. stage2_index = *block_index;
  1021. } else {
  1022. stage2_index = tables.stage2.size();
  1023. TRY(tables.stage2.try_extend(metadata.current_block));
  1024. TRY(metadata.unique_blocks.try_set(metadata.current_block, stage2_index));
  1025. }
  1026. TRY(tables.stage1.try_append(stage2_index));
  1027. metadata.current_block.clear_with_capacity();
  1028. }
  1029. return {};
  1030. }
  1031. static ErrorOr<void> create_code_point_tables(UnicodeData& unicode_data)
  1032. {
  1033. auto update_casing_tables = [&]<typename T>(u32 code_point, CodePointTables<T>& tables, CasingMetadata& metadata) -> ErrorOr<void> {
  1034. CasingTable casing {};
  1035. while (metadata.iterator != metadata.end) {
  1036. if (code_point < metadata.iterator->code_point)
  1037. break;
  1038. if (code_point == metadata.iterator->code_point) {
  1039. casing = move(metadata.iterator->casing);
  1040. break;
  1041. }
  1042. ++metadata.iterator;
  1043. }
  1044. TRY(update_tables(code_point, tables, metadata, casing));
  1045. return {};
  1046. };
  1047. auto update_property_tables = [&]<typename T>(u32 code_point, CodePointTables<T>& tables, PropertyMetadata& metadata) -> ErrorOr<void> {
  1048. static Unicode::CodePointRangeComparator comparator {};
  1049. for (auto& property_values : metadata.property_values) {
  1050. size_t ranges_to_remove = 0;
  1051. auto has_property = false;
  1052. for (auto const& range : property_values) {
  1053. if (auto comparison = comparator(code_point, range); comparison <= 0) {
  1054. has_property = comparison == 0;
  1055. break;
  1056. }
  1057. ++ranges_to_remove;
  1058. }
  1059. metadata.property_set.unchecked_append(has_property);
  1060. property_values.remove(0, ranges_to_remove);
  1061. }
  1062. TRY(update_tables(code_point, tables, metadata, metadata.property_set));
  1063. metadata.property_set.clear_with_capacity();
  1064. return {};
  1065. };
  1066. CasingMetadata casing_metadata { unicode_data.code_point_data };
  1067. auto general_category_metadata = TRY(PropertyMetadata::create(unicode_data.general_categories));
  1068. auto property_metadata = TRY(PropertyMetadata::create(unicode_data.prop_list));
  1069. auto script_metadata = TRY(PropertyMetadata::create(unicode_data.script_list));
  1070. auto script_extension_metadata = TRY(PropertyMetadata::create(unicode_data.script_extensions));
  1071. auto grapheme_break_metadata = TRY(PropertyMetadata::create(unicode_data.grapheme_break_props));
  1072. auto word_break_metadata = TRY(PropertyMetadata::create(unicode_data.word_break_props));
  1073. auto sentence_break_metadata = TRY(PropertyMetadata::create(unicode_data.sentence_break_props));
  1074. for (u32 code_point = 0; code_point <= MAX_CODE_POINT; ++code_point) {
  1075. TRY(update_casing_tables(code_point, unicode_data.casing_tables, casing_metadata));
  1076. TRY(update_property_tables(code_point, unicode_data.general_category_tables, general_category_metadata));
  1077. TRY(update_property_tables(code_point, unicode_data.property_tables, property_metadata));
  1078. TRY(update_property_tables(code_point, unicode_data.script_tables, script_metadata));
  1079. TRY(update_property_tables(code_point, unicode_data.script_extension_tables, script_extension_metadata));
  1080. TRY(update_property_tables(code_point, unicode_data.grapheme_break_tables, grapheme_break_metadata));
  1081. TRY(update_property_tables(code_point, unicode_data.word_break_tables, word_break_metadata));
  1082. TRY(update_property_tables(code_point, unicode_data.sentence_break_tables, sentence_break_metadata));
  1083. }
  1084. return {};
  1085. }
  1086. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1087. {
  1088. StringView generated_header_path;
  1089. StringView generated_implementation_path;
  1090. StringView unicode_data_path;
  1091. StringView special_casing_path;
  1092. StringView case_folding_path;
  1093. StringView derived_general_category_path;
  1094. StringView prop_list_path;
  1095. StringView derived_core_prop_path;
  1096. StringView derived_binary_prop_path;
  1097. StringView prop_alias_path;
  1098. StringView prop_value_alias_path;
  1099. StringView scripts_path;
  1100. StringView script_extensions_path;
  1101. StringView emoji_data_path;
  1102. StringView normalization_path;
  1103. StringView grapheme_break_path;
  1104. StringView word_break_path;
  1105. StringView sentence_break_path;
  1106. Core::ArgsParser args_parser;
  1107. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  1108. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  1109. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  1110. args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
  1111. args_parser.add_option(case_folding_path, "Path to CaseFolding.txt file", "case-folding-path", 'o', "case-folding-path");
  1112. args_parser.add_option(derived_general_category_path, "Path to DerivedGeneralCategory.txt file", "derived-general-category-path", 'g', "derived-general-category-path");
  1113. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  1114. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  1115. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  1116. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  1117. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  1118. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  1119. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  1120. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  1121. args_parser.add_option(normalization_path, "Path to DerivedNormalizationProps.txt file", "normalization-path", 'n', "normalization-path");
  1122. args_parser.add_option(grapheme_break_path, "Path to GraphemeBreakProperty.txt file", "grapheme-break-path", 'f', "grapheme-break-path");
  1123. args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path");
  1124. args_parser.add_option(sentence_break_path, "Path to SentenceBreakProperty.txt file", "sentence-break-path", 'i', "sentence-break-path");
  1125. args_parser.parse(arguments);
  1126. auto generated_header_file = TRY(open_file(generated_header_path, Core::File::OpenMode::Write));
  1127. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::File::OpenMode::Write));
  1128. auto unicode_data_file = TRY(open_file(unicode_data_path, Core::File::OpenMode::Read));
  1129. auto derived_general_category_file = TRY(open_file(derived_general_category_path, Core::File::OpenMode::Read));
  1130. auto special_casing_file = TRY(open_file(special_casing_path, Core::File::OpenMode::Read));
  1131. auto case_folding_file = TRY(open_file(case_folding_path, Core::File::OpenMode::Read));
  1132. auto prop_list_file = TRY(open_file(prop_list_path, Core::File::OpenMode::Read));
  1133. auto derived_core_prop_file = TRY(open_file(derived_core_prop_path, Core::File::OpenMode::Read));
  1134. auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path, Core::File::OpenMode::Read));
  1135. auto prop_alias_file = TRY(open_file(prop_alias_path, Core::File::OpenMode::Read));
  1136. auto prop_value_alias_file = TRY(open_file(prop_value_alias_path, Core::File::OpenMode::Read));
  1137. auto scripts_file = TRY(open_file(scripts_path, Core::File::OpenMode::Read));
  1138. auto script_extensions_file = TRY(open_file(script_extensions_path, Core::File::OpenMode::Read));
  1139. auto emoji_data_file = TRY(open_file(emoji_data_path, Core::File::OpenMode::Read));
  1140. auto normalization_file = TRY(open_file(normalization_path, Core::File::OpenMode::Read));
  1141. auto grapheme_break_file = TRY(open_file(grapheme_break_path, Core::File::OpenMode::Read));
  1142. auto word_break_file = TRY(open_file(word_break_path, Core::File::OpenMode::Read));
  1143. auto sentence_break_file = TRY(open_file(sentence_break_path, Core::File::OpenMode::Read));
  1144. UnicodeData unicode_data {};
  1145. TRY(parse_special_casing(*special_casing_file, unicode_data));
  1146. TRY(parse_case_folding(*case_folding_file, unicode_data));
  1147. TRY(parse_prop_list(*derived_general_category_file, unicode_data.general_categories));
  1148. TRY(parse_prop_list(*prop_list_file, unicode_data.prop_list));
  1149. TRY(parse_prop_list(*derived_core_prop_file, unicode_data.prop_list));
  1150. TRY(parse_prop_list(*derived_binary_prop_file, unicode_data.prop_list));
  1151. TRY(parse_prop_list(*emoji_data_file, unicode_data.prop_list));
  1152. TRY(parse_normalization_props(*normalization_file, unicode_data));
  1153. TRY(parse_alias_list(*prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases));
  1154. TRY(parse_prop_list(*scripts_file, unicode_data.script_list));
  1155. TRY(parse_prop_list(*script_extensions_file, unicode_data.script_extensions, true));
  1156. TRY(parse_prop_list(*grapheme_break_file, unicode_data.grapheme_break_props));
  1157. TRY(parse_prop_list(*word_break_file, unicode_data.word_break_props));
  1158. TRY(parse_prop_list(*sentence_break_file, unicode_data.sentence_break_props));
  1159. populate_general_category_unions(unicode_data.general_categories);
  1160. TRY(parse_unicode_data(*unicode_data_file, unicode_data));
  1161. TRY(parse_value_alias_list(*prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases));
  1162. TRY(parse_value_alias_list(*prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false));
  1163. TRY(normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases));
  1164. TRY(create_code_point_tables(unicode_data));
  1165. TRY(generate_unicode_data_header(*generated_header_file, unicode_data));
  1166. TRY(generate_unicode_data_implementation(*generated_implementation_file, unicode_data));
  1167. return 0;
  1168. }