GenerateUnicodeData.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  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/DeprecatedString.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. DeprecatedString locale;
  30. DeprecatedString 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/#Character_Decomposition_Mappings
  39. struct CodePointDecomposition {
  40. // `tag` is a string since it's used for codegen as an enum value.
  41. DeprecatedString tag { "Canonical"sv };
  42. size_t decomposition_index { 0 };
  43. size_t decomposition_size { 0 };
  44. };
  45. // https://www.unicode.org/reports/tr44/#PropList.txt
  46. using PropList = HashMap<DeprecatedString, Vector<Unicode::CodePointRange>>;
  47. // https://www.unicode.org/reports/tr44/#DerivedNormalizationProps.txt
  48. enum class QuickCheck {
  49. Yes,
  50. No,
  51. Maybe,
  52. };
  53. struct Normalization {
  54. Unicode::CodePointRange code_point_range;
  55. Vector<u32> value;
  56. QuickCheck quick_check { QuickCheck::Yes };
  57. };
  58. using NormalizationProps = HashMap<DeprecatedString, Vector<Normalization>>;
  59. struct CodePointName {
  60. Unicode::CodePointRange code_point_range;
  61. size_t name { 0 };
  62. };
  63. struct CasingTable {
  64. bool operator==(CasingTable const& other) const
  65. {
  66. return canonical_combining_class == other.canonical_combining_class
  67. && simple_lowercase_mapping == other.simple_lowercase_mapping
  68. && simple_uppercase_mapping == other.simple_uppercase_mapping
  69. && simple_titlecase_mapping == other.simple_titlecase_mapping
  70. && special_casing_indices == other.special_casing_indices
  71. && case_folding_indices == other.case_folding_indices;
  72. }
  73. u8 canonical_combining_class { 0 };
  74. Optional<u32> simple_uppercase_mapping;
  75. Optional<u32> simple_lowercase_mapping;
  76. Optional<u32> simple_titlecase_mapping;
  77. Vector<u32> special_casing_indices;
  78. Vector<u32> case_folding_indices;
  79. };
  80. // https://www.unicode.org/reports/tr44/#UnicodeData.txt
  81. struct CodePointData {
  82. u32 code_point { 0 };
  83. DeprecatedString name;
  84. Optional<size_t> abbreviation;
  85. DeprecatedString bidi_class;
  86. Optional<CodePointDecomposition> decomposition_mapping;
  87. Optional<i8> numeric_value_decimal;
  88. Optional<i8> numeric_value_digit;
  89. Optional<i8> numeric_value_numeric;
  90. bool bidi_mirrored { false };
  91. DeprecatedString unicode_1_name;
  92. DeprecatedString iso_comment;
  93. CasingTable casing;
  94. };
  95. struct BlockName {
  96. Unicode::CodePointRange code_point_range;
  97. size_t name { 0 };
  98. };
  99. using PropertyTable = Vector<bool>;
  100. static constexpr auto CODE_POINT_TABLES_MSB_COUNT = 16u;
  101. static_assert(CODE_POINT_TABLES_MSB_COUNT < 24u);
  102. static constexpr auto CODE_POINT_TABLES_LSB_COUNT = 24u - CODE_POINT_TABLES_MSB_COUNT;
  103. static constexpr auto CODE_POINT_TABLES_LSB_MASK = NumericLimits<u32>::max() >> (NumericLimits<u32>::digits() - CODE_POINT_TABLES_LSB_COUNT);
  104. template<typename PropertyType>
  105. struct CodePointTables {
  106. Vector<size_t> stage1;
  107. Vector<size_t> stage2;
  108. Vector<PropertyType> unique_properties;
  109. };
  110. struct CodePointBidiClass {
  111. Unicode::CodePointRange code_point_range;
  112. DeprecatedString bidi_class;
  113. };
  114. struct UnicodeData {
  115. UniqueStringStorage unique_strings;
  116. u32 code_points_with_decomposition_mapping { 0 };
  117. Vector<u32> decomposition_mappings;
  118. Vector<DeprecatedString> compatibility_tags;
  119. Vector<SpecialCasing> special_casing;
  120. u32 largest_special_casing_mapping_size { 0 };
  121. Vector<DeprecatedString> conditions;
  122. Vector<DeprecatedString> locales;
  123. Vector<CaseFolding> case_folding;
  124. u32 largest_case_folding_mapping_size { 0 };
  125. Vector<StringView> statuses;
  126. Vector<CodePointData> code_point_data;
  127. HashMap<u32, size_t> code_point_abbreviations;
  128. HashMap<u32, size_t> code_point_display_name_aliases;
  129. Vector<CodePointName> code_point_display_names;
  130. // https://www.unicode.org/reports/tr44/#General_Category_Values
  131. PropList general_categories;
  132. Vector<Alias> general_category_aliases;
  133. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  134. // any UCD file. Assigned code point ranges are derived as this generator is executed.
  135. // https://unicode.org/reports/tr18/#General_Category_Property
  136. PropList prop_list {
  137. { "Any"sv, { { 0, 0x10ffff } } },
  138. { "Assigned"sv, {} },
  139. { "ASCII"sv, { { 0, 0x7f } } },
  140. };
  141. Vector<Alias> prop_aliases;
  142. PropList script_list {
  143. { "Unknown"sv, {} },
  144. };
  145. Vector<Alias> script_aliases;
  146. PropList script_extensions;
  147. Vector<BlockName> block_display_names;
  148. // FIXME: We are not yet doing anything with this data. It will be needed for String.prototype.normalize.
  149. NormalizationProps normalization_props;
  150. PropList grapheme_break_props;
  151. PropList word_break_props;
  152. PropList sentence_break_props;
  153. CodePointTables<CasingTable> casing_tables;
  154. CodePointTables<PropertyTable> general_category_tables;
  155. CodePointTables<PropertyTable> property_tables;
  156. CodePointTables<PropertyTable> script_tables;
  157. CodePointTables<PropertyTable> script_extension_tables;
  158. CodePointTables<PropertyTable> grapheme_break_tables;
  159. CodePointTables<PropertyTable> word_break_tables;
  160. CodePointTables<PropertyTable> sentence_break_tables;
  161. HashTable<DeprecatedString> bidirectional_classes;
  162. Vector<CodePointBidiClass> code_point_bidirectional_classes;
  163. };
  164. static DeprecatedString sanitize_entry(DeprecatedString const& entry)
  165. {
  166. auto sanitized = entry.replace("-"sv, "_"sv, ReplaceMode::All);
  167. sanitized = sanitized.replace(" "sv, "_"sv, ReplaceMode::All);
  168. StringBuilder builder;
  169. bool next_is_upper = true;
  170. for (auto ch : sanitized) {
  171. if (next_is_upper)
  172. builder.append_code_point(to_ascii_uppercase(ch));
  173. else
  174. builder.append_code_point(ch);
  175. next_is_upper = ch == '_';
  176. }
  177. return builder.to_deprecated_string();
  178. }
  179. static Vector<u32> parse_code_point_list(StringView list)
  180. {
  181. Vector<u32> code_points;
  182. auto segments = list.split_view(' ');
  183. for (auto const& code_point : segments)
  184. code_points.append(AK::StringUtils::convert_to_uint_from_hex<u32>(code_point).value());
  185. return code_points;
  186. }
  187. static Unicode::CodePointRange parse_code_point_range(StringView list)
  188. {
  189. Unicode::CodePointRange code_point_range {};
  190. if (list.contains(".."sv)) {
  191. auto segments = list.split_view(".."sv);
  192. VERIFY(segments.size() == 2);
  193. auto begin = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  194. auto end = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[1]).value();
  195. code_point_range = { begin, end };
  196. } else {
  197. auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(list).value();
  198. code_point_range = { code_point, code_point };
  199. }
  200. return code_point_range;
  201. }
  202. static ErrorOr<void> parse_special_casing(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  203. {
  204. Array<u8, 1024> buffer;
  205. while (TRY(file.can_read_line())) {
  206. auto line = TRY(file.read_line(buffer));
  207. if (line.is_empty() || line.starts_with('#'))
  208. continue;
  209. if (auto index = line.find('#'); index.has_value())
  210. line = line.substring_view(0, *index);
  211. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  212. VERIFY(segments.size() == 5 || segments.size() == 6);
  213. SpecialCasing casing {};
  214. casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  215. casing.lowercase_mapping = parse_code_point_list(segments[1]);
  216. casing.titlecase_mapping = parse_code_point_list(segments[2]);
  217. casing.uppercase_mapping = parse_code_point_list(segments[3]);
  218. if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
  219. auto conditions = condition.split_view(' ', SplitBehavior::KeepEmpty);
  220. VERIFY(conditions.size() == 1 || conditions.size() == 2);
  221. if (conditions.size() == 2) {
  222. casing.locale = conditions[0];
  223. casing.condition = conditions[1];
  224. } else if (all_of(conditions[0], is_ascii_lower_alpha)) {
  225. casing.locale = conditions[0];
  226. } else {
  227. casing.condition = conditions[0];
  228. }
  229. if (!casing.locale.is_empty()) {
  230. casing.locale = DeprecatedString::formatted("{:c}{}", to_ascii_uppercase(casing.locale[0]), casing.locale.substring_view(1));
  231. if (!unicode_data.locales.contains_slow(casing.locale))
  232. unicode_data.locales.append(casing.locale);
  233. }
  234. casing.condition = casing.condition.replace("_"sv, ""sv, ReplaceMode::All);
  235. if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
  236. unicode_data.conditions.append(casing.condition);
  237. }
  238. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.lowercase_mapping.size());
  239. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.titlecase_mapping.size());
  240. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.uppercase_mapping.size());
  241. unicode_data.special_casing.append(move(casing));
  242. }
  243. quick_sort(unicode_data.special_casing, [](auto const& lhs, auto const& rhs) {
  244. if (lhs.code_point != rhs.code_point)
  245. return lhs.code_point < rhs.code_point;
  246. if (lhs.locale.is_empty() && !rhs.locale.is_empty())
  247. return false;
  248. if (!lhs.locale.is_empty() && rhs.locale.is_empty())
  249. return true;
  250. return lhs.locale < rhs.locale;
  251. });
  252. for (u32 i = 0; i < unicode_data.special_casing.size(); ++i)
  253. unicode_data.special_casing[i].index = i;
  254. return {};
  255. }
  256. static ErrorOr<void> parse_case_folding(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  257. {
  258. Array<u8, 1024> buffer;
  259. while (TRY(file.can_read_line())) {
  260. auto line = TRY(file.read_line(buffer));
  261. if (line.is_empty() || line.starts_with('#'))
  262. continue;
  263. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  264. VERIFY(segments.size() == 4);
  265. CaseFolding folding {};
  266. folding.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  267. folding.mapping = parse_code_point_list(segments[2]);
  268. switch (segments[1].trim_whitespace()[0]) {
  269. case 'C':
  270. folding.status = "Common"sv;
  271. break;
  272. case 'F':
  273. folding.status = "Full"sv;
  274. break;
  275. case 'S':
  276. folding.status = "Simple"sv;
  277. break;
  278. case 'T':
  279. folding.status = "Special"sv;
  280. break;
  281. }
  282. unicode_data.largest_case_folding_mapping_size = max(unicode_data.largest_case_folding_mapping_size, folding.mapping.size());
  283. if (!unicode_data.statuses.contains_slow(folding.status))
  284. unicode_data.statuses.append(folding.status);
  285. unicode_data.case_folding.append(move(folding));
  286. }
  287. quick_sort(unicode_data.case_folding, [](auto const& lhs, auto const& rhs) {
  288. if (lhs.code_point != rhs.code_point)
  289. return lhs.code_point < rhs.code_point;
  290. return lhs.status < rhs.status;
  291. });
  292. return {};
  293. }
  294. static ErrorOr<void> parse_prop_list(Core::InputBufferedFile& file, PropList& prop_list, bool multi_value_property = false, bool sanitize_property = false)
  295. {
  296. Array<u8, 1024> buffer;
  297. while (TRY(file.can_read_line())) {
  298. auto line = TRY(file.read_line(buffer));
  299. if (line.is_empty() || line.starts_with('#'))
  300. continue;
  301. if (auto index = line.find('#'); index.has_value())
  302. line = line.substring_view(0, *index);
  303. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  304. VERIFY(segments.size() == 2);
  305. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  306. Vector<StringView> properties;
  307. if (multi_value_property)
  308. properties = segments[1].trim_whitespace().split_view(' ');
  309. else
  310. properties = { segments[1].trim_whitespace() };
  311. for (auto& property : properties) {
  312. auto& code_points = prop_list.ensure(sanitize_property ? sanitize_entry(property).trim_whitespace().view() : property.trim_whitespace());
  313. code_points.append(code_point_range);
  314. }
  315. }
  316. return {};
  317. }
  318. static ErrorOr<void> parse_alias_list(Core::InputBufferedFile& file, PropList const& prop_list, Vector<Alias>& prop_aliases)
  319. {
  320. DeprecatedString current_property;
  321. Array<u8, 1024> buffer;
  322. auto append_alias = [&](auto alias, auto property) {
  323. // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip.
  324. if (alias == property)
  325. return;
  326. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  327. if (!prop_list.contains(property))
  328. return;
  329. prop_aliases.append({ property, alias });
  330. };
  331. while (TRY(file.can_read_line())) {
  332. auto line = TRY(file.read_line(buffer));
  333. if (line.is_empty() || line.starts_with('#')) {
  334. if (line.ends_with("Properties"sv))
  335. current_property = line.substring_view(2);
  336. continue;
  337. }
  338. // Note: For now, we only care about Binary Property aliases for Unicode property escapes.
  339. if (current_property != "Binary Properties"sv)
  340. continue;
  341. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  342. VERIFY((segments.size() == 2) || (segments.size() == 3));
  343. auto alias = segments[0].trim_whitespace();
  344. auto property = segments[1].trim_whitespace();
  345. append_alias(alias, property);
  346. if (segments.size() == 3) {
  347. alias = segments[2].trim_whitespace();
  348. append_alias(alias, property);
  349. }
  350. }
  351. return {};
  352. }
  353. static ErrorOr<void> parse_name_aliases(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  354. {
  355. Array<u8, 1024> buffer;
  356. while (TRY(file.can_read_line())) {
  357. auto line = TRY(file.read_line(buffer));
  358. if (line.is_empty() || line.starts_with('#'))
  359. continue;
  360. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  361. VERIFY(segments.size() == 3);
  362. auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0].trim_whitespace());
  363. auto alias = segments[1].trim_whitespace();
  364. auto reason = segments[2].trim_whitespace();
  365. if (reason == "abbreviation"sv) {
  366. auto index = unicode_data.unique_strings.ensure(alias);
  367. unicode_data.code_point_abbreviations.set(*code_point, index);
  368. } else if (reason.is_one_of("correction"sv, "control"sv)) {
  369. if (!unicode_data.code_point_display_name_aliases.contains(*code_point)) {
  370. auto index = unicode_data.unique_strings.ensure(alias);
  371. unicode_data.code_point_display_name_aliases.set(*code_point, index);
  372. }
  373. }
  374. }
  375. return {};
  376. }
  377. static ErrorOr<void> parse_value_alias_list(Core::InputBufferedFile& file, StringView desired_category, Vector<DeprecatedString> const& value_list, Vector<Alias>& prop_aliases, bool primary_value_is_first = true, bool sanitize_alias = false)
  378. {
  379. TRY(file.seek(0, SeekMode::SetPosition));
  380. Array<u8, 1024> buffer;
  381. auto append_alias = [&](auto alias, auto value) {
  382. // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip.
  383. if (alias == value)
  384. return;
  385. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  386. if (!value_list.contains_slow(value))
  387. return;
  388. prop_aliases.append({ value, alias });
  389. };
  390. while (TRY(file.can_read_line())) {
  391. auto line = TRY(file.read_line(buffer));
  392. if (line.is_empty() || line.starts_with('#'))
  393. continue;
  394. if (auto index = line.find('#'); index.has_value())
  395. line = line.substring_view(0, *index);
  396. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  397. auto category = segments[0].trim_whitespace();
  398. if (category != desired_category)
  399. continue;
  400. VERIFY((segments.size() == 3) || (segments.size() == 4));
  401. auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace();
  402. auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace();
  403. append_alias(sanitize_alias ? sanitize_entry(alias).view() : alias, value);
  404. if (segments.size() == 4) {
  405. alias = segments[3].trim_whitespace();
  406. append_alias(sanitize_alias ? sanitize_entry(alias).view() : alias, value);
  407. }
  408. }
  409. return {};
  410. }
  411. static ErrorOr<void> parse_normalization_props(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  412. {
  413. Array<u8, 1024> buffer;
  414. while (TRY(file.can_read_line())) {
  415. auto line = TRY(file.read_line(buffer));
  416. if (line.is_empty() || line.starts_with('#'))
  417. continue;
  418. if (auto index = line.find('#'); index.has_value())
  419. line = line.substring_view(0, *index);
  420. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  421. VERIFY((segments.size() == 2) || (segments.size() == 3));
  422. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  423. auto property = segments[1].trim_whitespace().to_deprecated_string();
  424. Vector<u32> value;
  425. QuickCheck quick_check = QuickCheck::Yes;
  426. if (segments.size() == 3) {
  427. auto value_or_quick_check = segments[2].trim_whitespace();
  428. if ((value_or_quick_check == "N"sv))
  429. quick_check = QuickCheck::No;
  430. else if ((value_or_quick_check == "M"sv))
  431. quick_check = QuickCheck::Maybe;
  432. else
  433. value = parse_code_point_list(value_or_quick_check);
  434. }
  435. auto& normalizations = unicode_data.normalization_props.ensure(property);
  436. normalizations.append({ code_point_range, move(value), quick_check });
  437. auto& prop_list = unicode_data.prop_list.ensure(property);
  438. prop_list.append(move(code_point_range));
  439. }
  440. return {};
  441. }
  442. static void add_canonical_code_point_name(Unicode::CodePointRange range, StringView name, UnicodeData& unicode_data)
  443. {
  444. // https://www.unicode.org/versions/Unicode15.0.0/ch04.pdf#G142981
  445. // FIXME: Implement the NR1 rules for Hangul syllables.
  446. struct CodePointNameFormat {
  447. Unicode::CodePointRange code_point_range;
  448. StringView name;
  449. };
  450. // These code point ranges are the NR2 set of name replacements defined by Table 4-8.
  451. constexpr Array<CodePointNameFormat, 16> s_ideographic_replacements { {
  452. { { 0x3400, 0x4DBF }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  453. { { 0x4E00, 0x9FFF }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  454. { { 0xF900, 0xFA6D }, "CJK COMPATIBILITY IDEOGRAPH-{:X}"sv },
  455. { { 0xFA70, 0xFAD9 }, "CJK COMPATIBILITY IDEOGRAPH-{:X}"sv },
  456. { { 0x17000, 0x187F7 }, "TANGUT IDEOGRAPH-{:X}"sv },
  457. { { 0x18B00, 0x18CD5 }, "KHITAN SMALL SCRIPT CHARACTER-{:X}"sv },
  458. { { 0x18D00, 0x18D08 }, "TANGUT IDEOGRAPH-{:X}"sv },
  459. { { 0x1B170, 0x1B2FB }, "NUSHU CHARACTER-{:X}"sv },
  460. { { 0x20000, 0x2A6DF }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  461. { { 0x2A700, 0x2B739 }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  462. { { 0x2B740, 0x2B81D }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  463. { { 0x2B820, 0x2CEA1 }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  464. { { 0x2CEB0, 0x2EBE0 }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  465. { { 0x2F800, 0x2FA1D }, "CJK COMPATIBILITY IDEOGRAPH-{:X}"sv },
  466. { { 0x30000, 0x3134A }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  467. { { 0x31350, 0x323AF }, "CJK UNIFIED IDEOGRAPH-{:X}"sv },
  468. } };
  469. auto it = find_if(s_ideographic_replacements.begin(), s_ideographic_replacements.end(),
  470. [&](auto const& replacement) {
  471. return replacement.code_point_range.first == range.first;
  472. });
  473. if (it != s_ideographic_replacements.end()) {
  474. auto index = unicode_data.unique_strings.ensure(it->name);
  475. unicode_data.code_point_display_names.append({ it->code_point_range, index });
  476. return;
  477. }
  478. it = find_if(s_ideographic_replacements.begin(), s_ideographic_replacements.end(),
  479. [&](auto const& replacement) {
  480. return (replacement.code_point_range.first <= range.first) && (range.first <= replacement.code_point_range.last);
  481. });
  482. if (it != s_ideographic_replacements.end()) {
  483. // Drop code points that will have been captured by a range defined by the ideographic replacements.
  484. return;
  485. }
  486. if (auto alias = unicode_data.code_point_display_name_aliases.get(range.first); alias.has_value()) {
  487. // NR4 states that control code points have a null string as their name. Our implementation
  488. // uses the control code's alias as its display name.
  489. unicode_data.code_point_display_names.append({ range, *alias });
  490. return;
  491. }
  492. auto index = unicode_data.unique_strings.ensure(name);
  493. unicode_data.code_point_display_names.append({ range, index });
  494. }
  495. static Optional<CodePointDecomposition> parse_decomposition_mapping(StringView string, UnicodeData& unicode_data)
  496. {
  497. if (string.is_empty())
  498. return {};
  499. CodePointDecomposition mapping;
  500. auto parts = string.split_view(' ');
  501. VERIFY(parts.size() > 0);
  502. if (parts.first().starts_with('<')) {
  503. auto const tag = parts.take_first().trim("<>"sv);
  504. mapping.tag = DeprecatedString::formatted("{:c}{}", to_ascii_uppercase(tag[0]), tag.substring_view(1));
  505. if (!unicode_data.compatibility_tags.contains_slow(mapping.tag))
  506. unicode_data.compatibility_tags.append(mapping.tag);
  507. }
  508. mapping.decomposition_index = unicode_data.decomposition_mappings.size();
  509. mapping.decomposition_size = parts.size();
  510. for (auto part : parts) {
  511. unicode_data.decomposition_mappings.append(AK::StringUtils::convert_to_uint_from_hex<u32>(part).value());
  512. }
  513. return mapping;
  514. }
  515. static ErrorOr<void> parse_block_display_names(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  516. {
  517. Array<u8, 1024> buffer;
  518. while (TRY(file.can_read_line())) {
  519. auto line = TRY(file.read_line(buffer));
  520. if (line.is_empty() || line.starts_with('#'))
  521. continue;
  522. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  523. VERIFY(segments.size() == 2);
  524. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  525. auto display_name = segments[1].trim_whitespace();
  526. auto index = unicode_data.unique_strings.ensure(display_name);
  527. unicode_data.block_display_names.append({ code_point_range, index });
  528. }
  529. TRY(file.seek(0, SeekMode::SetPosition));
  530. return {};
  531. }
  532. static ErrorOr<void> parse_unicode_data(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  533. {
  534. Optional<u32> code_point_range_start;
  535. auto& assigned_code_points = unicode_data.prop_list.find("Assigned"sv)->value;
  536. Optional<u32> assigned_code_point_range_start = 0;
  537. u32 previous_code_point = 0;
  538. Array<u8, 1024> buffer;
  539. while (TRY(file.can_read_line())) {
  540. auto line = TRY(file.read_line(buffer));
  541. if (line.is_empty())
  542. continue;
  543. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  544. VERIFY(segments.size() == 15);
  545. CodePointData data {};
  546. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  547. data.name = segments[1];
  548. data.casing.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
  549. data.bidi_class = segments[4];
  550. data.decomposition_mapping = parse_decomposition_mapping(segments[5], unicode_data);
  551. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  552. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  553. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  554. data.bidi_mirrored = segments[9] == "Y"sv;
  555. data.unicode_1_name = segments[10];
  556. data.iso_comment = segments[11];
  557. data.casing.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
  558. data.casing.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
  559. data.casing.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
  560. if (auto abbreviation = unicode_data.code_point_abbreviations.get(data.code_point); abbreviation.has_value())
  561. data.abbreviation = *abbreviation;
  562. if (!assigned_code_point_range_start.has_value())
  563. assigned_code_point_range_start = data.code_point;
  564. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>"sv)) {
  565. VERIFY(!code_point_range_start.has_value() && assigned_code_point_range_start.has_value());
  566. code_point_range_start = data.code_point;
  567. data.name = data.name.substring(1, data.name.length() - 9);
  568. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  569. assigned_code_point_range_start.clear();
  570. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>"sv)) {
  571. VERIFY(code_point_range_start.has_value());
  572. Unicode::CodePointRange code_point_range { *code_point_range_start, data.code_point };
  573. assigned_code_points.append(code_point_range);
  574. data.name = data.name.substring(1, data.name.length() - 8);
  575. code_point_range_start.clear();
  576. add_canonical_code_point_name(code_point_range, data.name, unicode_data);
  577. unicode_data.code_point_bidirectional_classes.append({ code_point_range, data.bidi_class });
  578. } else {
  579. add_canonical_code_point_name({ data.code_point, data.code_point }, data.name, unicode_data);
  580. unicode_data.code_point_bidirectional_classes.append({ { data.code_point, data.code_point }, data.bidi_class });
  581. if ((data.code_point > 0) && (data.code_point - previous_code_point) != 1) {
  582. VERIFY(assigned_code_point_range_start.has_value());
  583. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  584. assigned_code_point_range_start = data.code_point;
  585. }
  586. }
  587. for (auto const& casing : unicode_data.special_casing) {
  588. if (casing.code_point == data.code_point)
  589. data.casing.special_casing_indices.append(casing.index);
  590. }
  591. for (size_t i = 0; i < unicode_data.case_folding.size(); ++i) {
  592. if (auto const& folding = unicode_data.case_folding[i]; folding.code_point == data.code_point)
  593. data.casing.case_folding_indices.append(i);
  594. }
  595. unicode_data.code_points_with_decomposition_mapping += data.decomposition_mapping.has_value();
  596. unicode_data.bidirectional_classes.set(data.bidi_class, AK::HashSetExistingEntryBehavior::Keep);
  597. previous_code_point = data.code_point;
  598. unicode_data.code_point_data.append(move(data));
  599. }
  600. return {};
  601. }
  602. static ErrorOr<void> generate_unicode_data_header(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  603. {
  604. StringBuilder builder;
  605. SourceGenerator generator { builder };
  606. generator.set("special_casing_mapping_size", DeprecatedString::number(unicode_data.largest_special_casing_mapping_size));
  607. generator.set("case_folding_mapping_size", DeprecatedString::number(unicode_data.largest_case_folding_mapping_size));
  608. auto generate_enum = [&](StringView name, StringView default_, auto values, Vector<Alias> aliases = {}) {
  609. quick_sort(values);
  610. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  611. generator.set("name", name);
  612. generator.set("underlying", DeprecatedString::formatted("{}UnderlyingType", name));
  613. generator.set("type", ((values.size() + !default_.is_empty()) < 256) ? "u8"sv : "u16"sv);
  614. generator.append(R"~~~(
  615. using @underlying@ = @type@;
  616. enum class @name@ : @underlying@ {)~~~");
  617. if (!default_.is_empty()) {
  618. generator.set("default", default_);
  619. generator.append(R"~~~(
  620. @default@,)~~~");
  621. }
  622. for (auto const& value : values) {
  623. generator.set("value", value);
  624. generator.append(R"~~~(
  625. @value@,)~~~");
  626. }
  627. for (auto const& alias : aliases) {
  628. generator.set("alias", alias.alias);
  629. generator.set("value", alias.name);
  630. generator.append(R"~~~(
  631. @alias@ = @value@,)~~~");
  632. }
  633. generator.append(R"~~~(
  634. };
  635. )~~~");
  636. };
  637. generator.append(R"~~~(
  638. #pragma once
  639. #include <AK/Types.h>
  640. #include <LibUnicode/Forward.h>
  641. namespace Unicode {
  642. )~~~");
  643. generate_enum("Locale"sv, "None"sv, unicode_data.locales);
  644. generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
  645. generate_enum("CaseFoldingStatus"sv, {}, move(unicode_data.statuses));
  646. generate_enum("GeneralCategory"sv, {}, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  647. generate_enum("Property"sv, {}, unicode_data.prop_list.keys(), unicode_data.prop_aliases);
  648. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), unicode_data.script_aliases);
  649. generate_enum("GraphemeBreakProperty"sv, {}, unicode_data.grapheme_break_props.keys());
  650. generate_enum("WordBreakProperty"sv, {}, unicode_data.word_break_props.keys());
  651. generate_enum("SentenceBreakProperty"sv, {}, unicode_data.sentence_break_props.keys());
  652. generate_enum("CompatibilityFormattingTag"sv, "Canonical"sv, unicode_data.compatibility_tags);
  653. generate_enum("BidirectionalClass"sv, {}, unicode_data.bidirectional_classes.values());
  654. generator.append(R"~~~(
  655. struct SpecialCasing {
  656. u32 code_point { 0 };
  657. u32 lowercase_mapping[@special_casing_mapping_size@];
  658. u32 lowercase_mapping_size { 0 };
  659. u32 uppercase_mapping[@special_casing_mapping_size@];
  660. u32 uppercase_mapping_size { 0 };
  661. u32 titlecase_mapping[@special_casing_mapping_size@];
  662. u32 titlecase_mapping_size { 0 };
  663. Locale locale { Locale::None };
  664. Condition condition { Condition::None };
  665. };
  666. struct CaseFolding {
  667. u32 code_point { 0 };
  668. CaseFoldingStatus status { CaseFoldingStatus::Common };
  669. u32 mapping[@case_folding_mapping_size@];
  670. u32 mapping_size { 0 };
  671. };
  672. struct CodePointDecompositionRaw {
  673. u32 code_point { 0 };
  674. CompatibilityFormattingTag tag { CompatibilityFormattingTag::Canonical };
  675. size_t decomposition_index { 0 };
  676. size_t decomposition_count { 0 };
  677. };
  678. struct CodePointDecomposition {
  679. u32 code_point { 0 };
  680. CompatibilityFormattingTag tag { CompatibilityFormattingTag::Canonical };
  681. ReadonlySpan<u32> decomposition;
  682. };
  683. Optional<Locale> locale_from_string(StringView locale);
  684. ReadonlySpan<SpecialCasing> special_case_mapping(u32 code_point);
  685. ReadonlySpan<CaseFolding> case_folding_mapping(u32 code_point);
  686. }
  687. )~~~");
  688. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  689. return {};
  690. }
  691. static ErrorOr<void> generate_unicode_data_implementation(Core::InputBufferedFile& file, UnicodeData const& unicode_data)
  692. {
  693. StringBuilder builder;
  694. SourceGenerator generator { builder };
  695. generator.set("string_index_type"sv, unicode_data.unique_strings.type_that_fits());
  696. generator.set("special_casing_size", DeprecatedString::number(unicode_data.special_casing.size()));
  697. generator.set("case_folding_size", DeprecatedString::number(unicode_data.case_folding.size()));
  698. generator.set("CODE_POINT_TABLES_LSB_COUNT", TRY(String::number(CODE_POINT_TABLES_LSB_COUNT)));
  699. generator.set("CODE_POINT_TABLES_LSB_MASK", TRY(String::formatted("{:#x}", CODE_POINT_TABLES_LSB_MASK)));
  700. generator.append(R"~~~(
  701. #include <AK/Array.h>
  702. #include <AK/BinarySearch.h>
  703. #include <AK/CharacterTypes.h>
  704. #include <AK/Optional.h>
  705. #include <AK/Span.h>
  706. #include <AK/DeprecatedString.h>
  707. #include <AK/StringView.h>
  708. #include <LibUnicode/CharacterTypes.h>
  709. #include <LibUnicode/UnicodeData.h>
  710. #include <LibUnicode/Normalize.h>
  711. namespace Unicode {
  712. )~~~");
  713. unicode_data.unique_strings.generate(generator);
  714. auto append_list_and_size = [&](auto const& list, StringView format) {
  715. if (list.is_empty()) {
  716. generator.append(", {}, 0");
  717. return;
  718. }
  719. bool first = true;
  720. generator.append(", {");
  721. for (auto const& item : list) {
  722. generator.append(first ? " "sv : ", "sv);
  723. generator.append(DeprecatedString::formatted(format, item));
  724. first = false;
  725. }
  726. generator.append(DeprecatedString::formatted(" }}, {}", list.size()));
  727. };
  728. generator.append(R"~~~(
  729. static constexpr Array<SpecialCasing, @special_casing_size@> s_special_case { {)~~~");
  730. for (auto const& casing : unicode_data.special_casing) {
  731. generator.set("code_point", DeprecatedString::formatted("{:#x}", casing.code_point));
  732. generator.append(R"~~~(
  733. { @code_point@)~~~");
  734. constexpr auto format = "0x{:x}"sv;
  735. append_list_and_size(casing.lowercase_mapping, format);
  736. append_list_and_size(casing.uppercase_mapping, format);
  737. append_list_and_size(casing.titlecase_mapping, format);
  738. generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
  739. generator.append(", Locale::@locale@");
  740. generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
  741. generator.append(", Condition::@condition@");
  742. generator.append(" },");
  743. }
  744. generator.append(R"~~~(
  745. } };
  746. static constexpr Array<CaseFolding, @case_folding_size@> s_case_folding { {)~~~");
  747. for (auto const& folding : unicode_data.case_folding) {
  748. generator.set("code_point", DeprecatedString::formatted("{:#x}", folding.code_point));
  749. generator.set("status", folding.status);
  750. generator.append(R"~~~(
  751. { @code_point@, CaseFoldingStatus::@status@)~~~");
  752. append_list_and_size(folding.mapping, "0x{:x}"sv);
  753. generator.append(" },");
  754. }
  755. generator.append(R"~~~(
  756. } };
  757. struct CasingTable {
  758. u8 canonical_combining_class { 0 };
  759. i32 simple_uppercase_mapping { -1 };
  760. i32 simple_lowercase_mapping { -1 };
  761. i32 simple_titlecase_mapping { -1 };
  762. u32 special_casing_start_index { 0 };
  763. u32 special_casing_size { 0 };
  764. u32 case_folding_start_index { 0 };
  765. u32 case_folding_size { 0 };
  766. };
  767. struct CodePointAbbreviation {
  768. u32 code_point { 0 };
  769. @string_index_type@ abbreviation { 0 };
  770. };
  771. template<typename MappingType>
  772. struct CodePointComparator {
  773. constexpr int operator()(u32 code_point, MappingType const& mapping)
  774. {
  775. return code_point - mapping.code_point;
  776. }
  777. };
  778. struct BlockNameData {
  779. CodePointRange code_point_range {};
  780. @string_index_type@ display_name { 0 };
  781. };
  782. struct BlockNameComparator : public CodePointRangeComparator {
  783. constexpr int operator()(u32 code_point, BlockNameData const& name)
  784. {
  785. return CodePointRangeComparator::operator()(code_point, name.code_point_range);
  786. }
  787. };
  788. struct CodePointName {
  789. CodePointRange code_point_range {};
  790. @string_index_type@ display_name { 0 };
  791. };
  792. struct CodePointNameComparator : public CodePointRangeComparator {
  793. constexpr int operator()(u32 code_point, CodePointName const& name)
  794. {
  795. return CodePointRangeComparator::operator()(code_point, name.code_point_range);
  796. }
  797. };
  798. struct BidiClassData {
  799. CodePointRange code_point_range {};
  800. BidirectionalClass bidi_class {};
  801. };
  802. struct CodePointBidiClassComparator : public CodePointRangeComparator {
  803. constexpr int operator()(u32 code_point, BidiClassData const& bidi_class)
  804. {
  805. return CodePointRangeComparator::operator()(code_point, bidi_class.code_point_range);
  806. }
  807. };
  808. )~~~");
  809. generator.set("decomposition_mappings_size", DeprecatedString::number(unicode_data.decomposition_mappings.size()));
  810. generator.append("\nstatic constexpr Array<u32, @decomposition_mappings_size@> s_decomposition_mappings_data { ");
  811. generator.append(DeprecatedString::join(", "sv, unicode_data.decomposition_mappings, "{:#x}"sv));
  812. generator.append(" };\n");
  813. auto append_code_point_mappings = [&](StringView name, StringView mapping_type, u32 size, auto mapping_getter) {
  814. generator.set("name", name);
  815. generator.set("mapping_type", mapping_type);
  816. generator.set("size", DeprecatedString::number(size));
  817. generator.append(R"~~~(
  818. static constexpr Array<@mapping_type@, @size@> s_@name@_mappings { {
  819. )~~~");
  820. constexpr size_t max_mappings_per_row = 20;
  821. size_t mappings_in_current_row = 0;
  822. for (auto const& data : unicode_data.code_point_data) {
  823. auto mapping = mapping_getter(data);
  824. if constexpr (requires { mapping.has_value(); }) {
  825. if (!mapping.has_value())
  826. continue;
  827. } else {
  828. if (mapping.is_empty())
  829. continue;
  830. }
  831. if (mappings_in_current_row++ > 0)
  832. generator.append(" ");
  833. generator.set("code_point", DeprecatedString::formatted("{:#x}", data.code_point));
  834. generator.append("{ @code_point@");
  835. if constexpr (IsSame<decltype(mapping), Optional<u32>> || IsSame<decltype(mapping), Optional<size_t>>) {
  836. generator.set("mapping", DeprecatedString::formatted("{:#x}", *mapping));
  837. generator.append(", @mapping@ },");
  838. } else if constexpr (IsSame<decltype(mapping), Optional<CodePointDecomposition>>) {
  839. generator.set("tag", mapping->tag);
  840. generator.set("start", DeprecatedString::number(mapping->decomposition_index));
  841. generator.set("size", DeprecatedString::number(mapping->decomposition_size));
  842. generator.append(", CompatibilityFormattingTag::@tag@, @start@, @size@ },");
  843. } else {
  844. append_list_and_size(mapping, "&s_@name@[{}]"sv);
  845. generator.append(" },");
  846. }
  847. if (mappings_in_current_row == max_mappings_per_row) {
  848. mappings_in_current_row = 0;
  849. generator.append("\n ");
  850. }
  851. }
  852. generator.append(R"~~~(
  853. } };
  854. )~~~");
  855. };
  856. append_code_point_mappings("abbreviation"sv, "CodePointAbbreviation"sv, unicode_data.code_point_abbreviations.size(), [](auto const& data) { return data.abbreviation; });
  857. append_code_point_mappings("decomposition"sv, "CodePointDecompositionRaw"sv, unicode_data.code_points_with_decomposition_mapping, [](auto const& data) { return data.decomposition_mapping; });
  858. auto append_casing_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  859. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  860. generator.set("size", TRY(String::number(unique_properties.size())));
  861. auto optional_code_point_to_string = [](auto const& code_point) -> ErrorOr<String> {
  862. if (!code_point.has_value())
  863. return "-1"_string;
  864. return String::number(*code_point);
  865. };
  866. auto first_index_to_string = [](auto const& list) -> ErrorOr<String> {
  867. if (list.is_empty())
  868. return "0"_string;
  869. return String::number(list.first());
  870. };
  871. generator.append(R"~~~(
  872. static constexpr Array<CasingTable, @size@> @name@ { {)~~~");
  873. for (auto const& casing : unique_properties) {
  874. generator.set("canonical_combining_class", TRY(String::number(casing.canonical_combining_class)));
  875. generator.set("simple_uppercase_mapping", TRY(optional_code_point_to_string(casing.simple_uppercase_mapping)));
  876. generator.set("simple_lowercase_mapping", TRY(optional_code_point_to_string(casing.simple_lowercase_mapping)));
  877. generator.set("simple_titlecase_mapping", TRY(optional_code_point_to_string(casing.simple_titlecase_mapping)));
  878. generator.set("special_casing_start_index", TRY(first_index_to_string(casing.special_casing_indices)));
  879. generator.set("special_casing_size", TRY(String::number(casing.special_casing_indices.size())));
  880. generator.set("case_folding_start_index", TRY(first_index_to_string(casing.case_folding_indices)));
  881. generator.set("case_folding_size", TRY(String::number(casing.case_folding_indices.size())));
  882. generator.append(R"~~~(
  883. { @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@ },)~~~");
  884. }
  885. generator.append(R"~~~(
  886. } };
  887. )~~~");
  888. return {};
  889. };
  890. auto append_property_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  891. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  892. generator.set("outer_size", TRY(String::number(unique_properties.size())));
  893. generator.set("inner_size", TRY(String::number(unique_properties[0].size())));
  894. generator.append(R"~~~(
  895. static constexpr Array<Array<bool, @inner_size@>, @outer_size@> @name@ { {)~~~");
  896. for (auto const& property_set : unique_properties) {
  897. generator.append(R"~~~(
  898. { )~~~");
  899. for (auto value : property_set) {
  900. generator.set("value", TRY(String::formatted("{}", value)));
  901. generator.append("@value@, ");
  902. }
  903. generator.append(" },");
  904. }
  905. generator.append(R"~~~(
  906. } };
  907. )~~~");
  908. return {};
  909. };
  910. auto append_code_point_tables = [&](StringView collection_snake, auto const& tables, auto& append_unique_properties) -> ErrorOr<void> {
  911. auto append_stage = [&](auto const& stage, auto name, auto type) -> ErrorOr<void> {
  912. generator.set("name", TRY(String::formatted("{}_{}", collection_snake, name)));
  913. generator.set("size", TRY(String::number(stage.size())));
  914. generator.set("type", type);
  915. generator.append(R"~~~(
  916. static constexpr Array<@type@, @size@> @name@ { {
  917. )~~~");
  918. static constexpr size_t max_values_per_row = 300;
  919. size_t values_in_current_row = 0;
  920. for (auto value : stage) {
  921. if (values_in_current_row++ > 0)
  922. generator.append(", ");
  923. generator.set("value", TRY(String::number(value)));
  924. generator.append("@value@");
  925. if (values_in_current_row == max_values_per_row) {
  926. values_in_current_row = 0;
  927. generator.append(",\n ");
  928. }
  929. }
  930. generator.append(R"~~~(
  931. } };
  932. )~~~");
  933. return {};
  934. };
  935. TRY(append_stage(tables.stage1, "stage1"sv, "u16"sv));
  936. TRY(append_stage(tables.stage2, "stage2"sv, "u16"sv));
  937. TRY(append_unique_properties(collection_snake, tables.unique_properties));
  938. return {};
  939. };
  940. TRY(append_code_point_tables("s_casings"sv, unicode_data.casing_tables, append_casing_table));
  941. TRY(append_code_point_tables("s_general_categories"sv, unicode_data.general_category_tables, append_property_table));
  942. TRY(append_code_point_tables("s_properties"sv, unicode_data.property_tables, append_property_table));
  943. TRY(append_code_point_tables("s_scripts"sv, unicode_data.script_tables, append_property_table));
  944. TRY(append_code_point_tables("s_script_extensions"sv, unicode_data.script_extension_tables, append_property_table));
  945. TRY(append_code_point_tables("s_grapheme_break_properties"sv, unicode_data.grapheme_break_tables, append_property_table));
  946. TRY(append_code_point_tables("s_word_break_properties"sv, unicode_data.word_break_tables, append_property_table));
  947. TRY(append_code_point_tables("s_sentence_break_properties"sv, unicode_data.sentence_break_tables, append_property_table));
  948. auto append_code_point_display_names = [&](StringView type, StringView name, auto const& display_names) {
  949. constexpr size_t max_values_per_row = 30;
  950. size_t values_in_current_row = 0;
  951. generator.set("type", type);
  952. generator.set("name", name);
  953. generator.set("size", DeprecatedString::number(display_names.size()));
  954. generator.append(R"~~~(
  955. static constexpr Array<@type@, @size@> @name@ { {
  956. )~~~");
  957. for (auto const& display_name : display_names) {
  958. if (values_in_current_row++ > 0)
  959. generator.append(", ");
  960. generator.set("first", DeprecatedString::formatted("{:#x}", display_name.code_point_range.first));
  961. generator.set("last", DeprecatedString::formatted("{:#x}", display_name.code_point_range.last));
  962. generator.set("name", DeprecatedString::number(display_name.name));
  963. generator.append("{ { @first@, @last@ }, @name@ }");
  964. if (values_in_current_row == max_values_per_row) {
  965. values_in_current_row = 0;
  966. generator.append(",\n ");
  967. }
  968. }
  969. generator.append(R"~~~(
  970. } };
  971. )~~~");
  972. };
  973. append_code_point_display_names("BlockNameData"sv, "s_block_display_names"sv, unicode_data.block_display_names);
  974. append_code_point_display_names("CodePointName"sv, "s_code_point_display_names"sv, unicode_data.code_point_display_names);
  975. {
  976. constexpr size_t max_bidi_classes_per_row = 20;
  977. size_t bidi_classes_in_current_row = 0;
  978. generator.set("size"sv, DeprecatedString::number(unicode_data.code_point_bidirectional_classes.size()));
  979. generator.append(R"~~~(
  980. static constexpr Array<BidiClassData, @size@> s_bidirectional_classes { {
  981. )~~~");
  982. for (auto const& data : unicode_data.code_point_bidirectional_classes) {
  983. if (bidi_classes_in_current_row++ > 0)
  984. generator.append(", ");
  985. generator.set("first", DeprecatedString::formatted("{:#x}", data.code_point_range.first));
  986. generator.set("last", DeprecatedString::formatted("{:#x}", data.code_point_range.last));
  987. generator.set("bidi_class", data.bidi_class);
  988. generator.append("{ { @first@, @last@ }, BidirectionalClass::@bidi_class@ }");
  989. if (bidi_classes_in_current_row == max_bidi_classes_per_row) {
  990. bidi_classes_in_current_row = 0;
  991. generator.append(",\n ");
  992. }
  993. }
  994. generator.append(R"~~~(
  995. } };
  996. )~~~");
  997. }
  998. generator.append(R"~~~(
  999. Optional<StringView> code_point_block_display_name(u32 code_point)
  1000. {
  1001. if (auto const* entry = binary_search(s_block_display_names, code_point, nullptr, BlockNameComparator {}))
  1002. return decode_string(entry->display_name);
  1003. return {};
  1004. }
  1005. ReadonlySpan<BlockName> block_display_names()
  1006. {
  1007. static auto display_names = []() {
  1008. Array<BlockName, s_block_display_names.size()> display_names;
  1009. for (size_t i = 0; i < s_block_display_names.size(); ++i) {
  1010. auto const& display_name = s_block_display_names[i];
  1011. display_names[i] = { display_name.code_point_range, decode_string(display_name.display_name) };
  1012. }
  1013. return display_names;
  1014. }();
  1015. return display_names.span();
  1016. }
  1017. Optional<DeprecatedString> code_point_display_name(u32 code_point)
  1018. {
  1019. if (auto const* entry = binary_search(s_code_point_display_names, code_point, nullptr, CodePointNameComparator {})) {
  1020. auto display_name = decode_string(entry->display_name);
  1021. if (display_name.ends_with("{:X}"sv))
  1022. return DeprecatedString::formatted(display_name, code_point);
  1023. return display_name;
  1024. }
  1025. return {};
  1026. }
  1027. static CasingTable const& casing_table_for_code_point(u32 code_point)
  1028. {
  1029. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  1030. auto stage2_index = s_casings_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  1031. auto unique_properties_index = s_casings_stage2[stage2_index];
  1032. return s_casings_unique_properties[unique_properties_index];
  1033. }
  1034. )~~~");
  1035. auto append_code_point_mapping_search = [&](StringView method, StringView mapping, Optional<StringView> const& fallback = {}) {
  1036. generator.set("method", method);
  1037. generator.set("mapping", mapping);
  1038. generator.append(R"~~~(
  1039. u32 @method@(u32 code_point)
  1040. {
  1041. auto const& casing_table = casing_table_for_code_point(code_point);
  1042. auto mapping = casing_table.@mapping@;
  1043. )~~~");
  1044. if (fallback.has_value()) {
  1045. generator.set("fallback", *fallback);
  1046. generator.append(R"~~~(
  1047. return mapping == -1 ? @fallback@ : static_cast<u32>(mapping);)~~~");
  1048. } else {
  1049. generator.append(R"~~~(
  1050. return mapping;)~~~");
  1051. }
  1052. generator.append(R"~~~(
  1053. }
  1054. )~~~");
  1055. };
  1056. append_code_point_mapping_search("canonical_combining_class"sv, "canonical_combining_class"sv);
  1057. append_code_point_mapping_search("to_unicode_uppercase"sv, "simple_uppercase_mapping"sv, "code_point"sv);
  1058. append_code_point_mapping_search("to_unicode_lowercase"sv, "simple_lowercase_mapping"sv, "code_point"sv);
  1059. append_code_point_mapping_search("to_unicode_titlecase"sv, "simple_titlecase_mapping"sv, "code_point"sv);
  1060. generator.append(R"~~~(
  1061. ReadonlySpan<SpecialCasing> special_case_mapping(u32 code_point)
  1062. {
  1063. auto const& casing_table = casing_table_for_code_point(code_point);
  1064. if (casing_table.special_casing_size == 0)
  1065. return {};
  1066. return s_special_case.span().slice(casing_table.special_casing_start_index, casing_table.special_casing_size);
  1067. }
  1068. ReadonlySpan<CaseFolding> case_folding_mapping(u32 code_point)
  1069. {
  1070. auto const& casing_table = casing_table_for_code_point(code_point);
  1071. if (casing_table.case_folding_size == 0)
  1072. return {};
  1073. return s_case_folding.span().slice(casing_table.case_folding_start_index, casing_table.case_folding_size);
  1074. }
  1075. Optional<StringView> code_point_abbreviation(u32 code_point)
  1076. {
  1077. auto const* mapping = binary_search(s_abbreviation_mappings, code_point, nullptr, CodePointComparator<CodePointAbbreviation> {});
  1078. if (mapping == nullptr)
  1079. return {};
  1080. if (mapping->abbreviation == 0)
  1081. return {};
  1082. return decode_string(mapping->abbreviation);
  1083. }
  1084. Optional<CodePointDecomposition const> code_point_decomposition(u32 code_point)
  1085. {
  1086. auto const* mapping = binary_search(s_decomposition_mappings, code_point, nullptr, CodePointComparator<CodePointDecompositionRaw> {});
  1087. if (mapping == nullptr)
  1088. return {};
  1089. return CodePointDecomposition { mapping->code_point, mapping->tag, ReadonlySpan<u32> { s_decomposition_mappings_data.data() + mapping->decomposition_index, mapping->decomposition_count } };
  1090. }
  1091. Optional<CodePointDecomposition const> code_point_decomposition_by_index(size_t index)
  1092. {
  1093. if (index >= s_decomposition_mappings.size())
  1094. return {};
  1095. auto const& mapping = s_decomposition_mappings[index];
  1096. return CodePointDecomposition { mapping.code_point, mapping.tag, ReadonlySpan<u32> { s_decomposition_mappings_data.data() + mapping.decomposition_index, mapping.decomposition_count } };
  1097. }
  1098. Optional<BidirectionalClass> bidirectional_class(u32 code_point)
  1099. {
  1100. if (auto const* entry = binary_search(s_bidirectional_classes, code_point, nullptr, CodePointBidiClassComparator {}))
  1101. return entry->bidi_class;
  1102. return {};
  1103. }
  1104. )~~~");
  1105. auto append_prop_search = [&](StringView enum_title, StringView enum_snake, StringView collection_name) -> ErrorOr<void> {
  1106. generator.set("enum_title", enum_title);
  1107. generator.set("enum_snake", enum_snake);
  1108. generator.set("collection_name", collection_name);
  1109. generator.append(R"~~~(
  1110. bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@)
  1111. {
  1112. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  1113. auto stage2_index = @collection_name@_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  1114. auto unique_properties_index = @collection_name@_stage2[stage2_index];
  1115. auto const& property_set = @collection_name@_unique_properties[unique_properties_index];
  1116. return property_set[to_underlying(@enum_snake@)];
  1117. }
  1118. )~~~");
  1119. return {};
  1120. };
  1121. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& prop_list, Vector<Alias> const& aliases) -> ErrorOr<void> {
  1122. HashValueMap<StringView> hashes;
  1123. TRY(hashes.try_ensure_capacity(prop_list.size() + aliases.size()));
  1124. ValueFromStringOptions options {};
  1125. for (auto const& prop : prop_list) {
  1126. if constexpr (IsSame<RemoveCVReference<decltype(prop)>, DeprecatedString>) {
  1127. hashes.set(CaseInsensitiveASCIIStringViewTraits::hash(prop), prop);
  1128. options.sensitivity = CaseSensitivity::CaseInsensitive;
  1129. } else {
  1130. hashes.set(prop.key.hash(), prop.key);
  1131. }
  1132. }
  1133. for (auto const& alias : aliases)
  1134. hashes.set(alias.alias.hash(), alias.alias);
  1135. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes), options);
  1136. return {};
  1137. };
  1138. TRY(append_from_string("Locale"sv, "locale"sv, unicode_data.locales, {}));
  1139. TRY(append_prop_search("GeneralCategory"sv, "general_category"sv, "s_general_categories"sv));
  1140. TRY(append_from_string("GeneralCategory"sv, "general_category"sv, unicode_data.general_categories, unicode_data.general_category_aliases));
  1141. TRY(append_prop_search("Property"sv, "property"sv, "s_properties"sv));
  1142. TRY(append_from_string("Property"sv, "property"sv, unicode_data.prop_list, unicode_data.prop_aliases));
  1143. TRY(append_prop_search("Script"sv, "script"sv, "s_scripts"sv));
  1144. TRY(append_prop_search("Script"sv, "script_extension"sv, "s_script_extensions"sv));
  1145. TRY(append_from_string("Script"sv, "script"sv, unicode_data.script_list, unicode_data.script_aliases));
  1146. TRY(append_prop_search("GraphemeBreakProperty"sv, "grapheme_break_property"sv, "s_grapheme_break_properties"sv));
  1147. TRY(append_prop_search("WordBreakProperty"sv, "word_break_property"sv, "s_word_break_properties"sv));
  1148. TRY(append_prop_search("SentenceBreakProperty"sv, "sentence_break_property"sv, "s_sentence_break_properties"sv));
  1149. TRY(append_from_string("BidirectionalClass"sv, "bidirectional_class"sv, unicode_data.bidirectional_classes, {}));
  1150. generator.append(R"~~~(
  1151. }
  1152. )~~~");
  1153. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  1154. return {};
  1155. }
  1156. static Vector<u32> flatten_code_point_ranges(Vector<Unicode::CodePointRange> const& code_points)
  1157. {
  1158. Vector<u32> flattened;
  1159. for (auto const& range : code_points) {
  1160. flattened.grow_capacity(range.last - range.first);
  1161. for (u32 code_point = range.first; code_point <= range.last; ++code_point)
  1162. flattened.append(code_point);
  1163. }
  1164. return flattened;
  1165. }
  1166. static Vector<Unicode::CodePointRange> form_code_point_ranges(Vector<u32> code_points)
  1167. {
  1168. Vector<Unicode::CodePointRange> ranges;
  1169. u32 range_start = code_points[0];
  1170. u32 range_end = range_start;
  1171. for (size_t i = 1; i < code_points.size(); ++i) {
  1172. u32 code_point = code_points[i];
  1173. if ((code_point - range_end) == 1) {
  1174. range_end = code_point;
  1175. } else {
  1176. ranges.append({ range_start, range_end });
  1177. range_start = code_point;
  1178. range_end = code_point;
  1179. }
  1180. }
  1181. ranges.append({ range_start, range_end });
  1182. return ranges;
  1183. }
  1184. static void sort_and_merge_code_point_ranges(Vector<Unicode::CodePointRange>& code_points)
  1185. {
  1186. quick_sort(code_points, [](auto const& range1, auto const& range2) {
  1187. return range1.first < range2.first;
  1188. });
  1189. for (size_t i = 0; i < code_points.size() - 1;) {
  1190. if (code_points[i].last >= code_points[i + 1].first) {
  1191. code_points[i].last = max(code_points[i].last, code_points[i + 1].last);
  1192. code_points.remove(i + 1);
  1193. } else {
  1194. ++i;
  1195. }
  1196. }
  1197. auto all_code_points = flatten_code_point_ranges(code_points);
  1198. code_points = form_code_point_ranges(all_code_points);
  1199. }
  1200. static void populate_general_category_unions(PropList& general_categories)
  1201. {
  1202. // The Unicode standard defines General Category values which are not in any UCD file. These
  1203. // values are simply unions of other values.
  1204. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  1205. auto populate_union = [&](auto alias, auto categories) {
  1206. auto& code_points = general_categories.ensure(alias);
  1207. for (auto const& category : categories)
  1208. code_points.extend(general_categories.find(category)->value);
  1209. sort_and_merge_code_point_ranges(code_points);
  1210. };
  1211. populate_union("LC"sv, Array { "Ll"sv, "Lu"sv, "Lt"sv });
  1212. populate_union("L"sv, Array { "Lu"sv, "Ll"sv, "Lt"sv, "Lm"sv, "Lo"sv });
  1213. populate_union("M"sv, Array { "Mn"sv, "Mc"sv, "Me"sv });
  1214. populate_union("N"sv, Array { "Nd"sv, "Nl"sv, "No"sv });
  1215. populate_union("P"sv, Array { "Pc"sv, "Pd"sv, "Ps"sv, "Pe"sv, "Pi"sv, "Pf"sv, "Po"sv });
  1216. populate_union("S"sv, Array { "Sm"sv, "Sc"sv, "Sk"sv, "So"sv });
  1217. populate_union("Z"sv, Array { "Zs"sv, "Zl"sv, "Zp"sv });
  1218. populate_union("C"sv, Array { "Cc"sv, "Cf"sv, "Cs"sv, "Co"sv, "Cn"sv });
  1219. }
  1220. static ErrorOr<void> normalize_script_extensions(PropList& script_extensions, PropList const& script_list, Vector<Alias> const& script_aliases)
  1221. {
  1222. // The ScriptExtensions UCD file lays out its code point ranges rather uniquely compared to
  1223. // other files. The Script listed on each line may either be a full Script string or an aliased
  1224. // abbreviation. Further, the extensions may or may not include the base Script list. Normalize
  1225. // the extensions here to be keyed by the full Script name and always include the base list.
  1226. auto extensions = move(script_extensions);
  1227. script_extensions = TRY(script_list.clone());
  1228. for (auto const& extension : extensions) {
  1229. auto it = find_if(script_aliases.begin(), script_aliases.end(), [&](auto const& alias) { return extension.key == alias.alias; });
  1230. auto const& key = (it == script_aliases.end()) ? extension.key : it->name;
  1231. auto& code_points = script_extensions.find(key)->value;
  1232. code_points.extend(extension.value);
  1233. sort_and_merge_code_point_ranges(code_points);
  1234. }
  1235. // Lastly, the Common and Inherited script extensions are special. They must not contain any
  1236. // code points which appear in other script extensions. The ScriptExtensions UCD file does not
  1237. // list these extensions, therefore this peculiarity must be handled programmatically.
  1238. // https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values
  1239. auto code_point_has_other_extension = [&](StringView key, u32 code_point) {
  1240. for (auto const& extension : extensions) {
  1241. if (extension.key == key)
  1242. continue;
  1243. if (any_of(extension.value, [&](auto const& r) { return (r.first <= code_point) && (code_point <= r.last); }))
  1244. return true;
  1245. }
  1246. return false;
  1247. };
  1248. auto get_code_points_without_other_extensions = [&](StringView key) {
  1249. auto code_points = flatten_code_point_ranges(script_list.find(key)->value);
  1250. code_points.remove_all_matching([&](u32 c) { return code_point_has_other_extension(key, c); });
  1251. return code_points;
  1252. };
  1253. auto common_code_points = get_code_points_without_other_extensions("Common"sv);
  1254. script_extensions.set("Common"sv, form_code_point_ranges(common_code_points));
  1255. auto inherited_code_points = get_code_points_without_other_extensions("Inherited"sv);
  1256. script_extensions.set("Inherited"sv, form_code_point_ranges(inherited_code_points));
  1257. return {};
  1258. }
  1259. struct CasingMetadata {
  1260. using ConstIterator = typename Vector<CodePointData>::ConstIterator;
  1261. CasingMetadata(Vector<CodePointData> const& code_point_data)
  1262. : iterator(code_point_data.begin())
  1263. , end(code_point_data.end())
  1264. {
  1265. }
  1266. ConstIterator iterator;
  1267. ConstIterator const end;
  1268. Vector<size_t> current_block;
  1269. HashMap<decltype(current_block), size_t> unique_blocks;
  1270. };
  1271. struct PropertyMetadata {
  1272. static ErrorOr<PropertyMetadata> create(PropList& property_list)
  1273. {
  1274. PropertyMetadata data;
  1275. TRY(data.property_values.try_ensure_capacity(property_list.size()));
  1276. TRY(data.property_set.try_ensure_capacity(property_list.size()));
  1277. auto property_names = property_list.keys();
  1278. quick_sort(property_names);
  1279. for (auto& property_name : property_names) {
  1280. auto& code_point_ranges = property_list.get(property_name).value();
  1281. data.property_values.unchecked_append(move(code_point_ranges));
  1282. }
  1283. return data;
  1284. }
  1285. Vector<typename PropList::ValueType> property_values;
  1286. PropertyTable property_set;
  1287. Vector<size_t> current_block;
  1288. HashMap<decltype(current_block), size_t> unique_blocks;
  1289. };
  1290. // The goal here is to produce a set of tables that represent a category of code point properties for every code point.
  1291. // The most naive method would be to generate a single table per category, each with one entry per code point. Each of
  1292. // those tables would have a size of 0x10ffff though, which is a non-starter. Instead, we create a set of 2-stage lookup
  1293. // tables per category.
  1294. //
  1295. // To do so, it's important to note that Unicode tends to organize code points with similar properties together. This
  1296. // leads to long series of code points with identical properties. Therefore, if we divide the 0x10ffff code points into
  1297. // fixed-size blocks, many of those blocks will also be identical.
  1298. //
  1299. // So we iterate over every code point, classifying each one for the category of interest. We represent a classification
  1300. // as a list of booleans. We store the classification in the CodePointTables::unique_properties list for this category.
  1301. // As the name implies, this list is de-duplicated; we store the index into this list in a separate list, which we call
  1302. // a "block".
  1303. //
  1304. // As we iterate, we "pause" every BLOCK_SIZE code points to examine the block. If the block is unique so far, we extend
  1305. // CodePointTables::stage2 with the entries of that block (so CodePointTables::stage2 is also a list of indices into
  1306. // CodePointTables::unique_properties). We then append the index of the start of that block in CodePointTables::stage2
  1307. // to CodePointTables::stage1.
  1308. //
  1309. // The value of BLOCK_SIZE is determined by CodePointTables::MSB_COUNT and CodePointTables::LSB_COUNT. We need 24 bits
  1310. // to describe all code points; the blocks we create are based on splitting these bits into 2 segments. We currently use
  1311. // a 16:8 bit split. So when perform a runtime lookup of a code point in the 2-stage tables, we:
  1312. //
  1313. // 1. Use most-significant 16 bits of the code point as the index into CodePointTables::stage1. That value is the
  1314. // index into CodePointTables::stage2 of the start of the block that contains properties for this code point.
  1315. //
  1316. // 2. Add the least-significant 8 bits of the code point to that value, to use as the index into
  1317. // CodePointTables::stage2. As described above, that value is the index into CodePointTables::unique_properties,
  1318. // which contains the classification for this code point.
  1319. //
  1320. // Using the code point GeneralCategory as an example, we end up with a CodePointTables::stage1 with a size of ~4000,
  1321. // a CodePointTables::stage2 with a size of ~40,000, and a CodePointTables::unique_properties with a size of ~30. So
  1322. // this process reduces over 1 million entries (0x10ffff) to ~44,030.
  1323. //
  1324. // For much more in-depth reading, see: https://icu.unicode.org/design/struct/utrie
  1325. static ErrorOr<void> create_code_point_tables(UnicodeData& unicode_data)
  1326. {
  1327. static constexpr auto MAX_CODE_POINT = 0x10ffffu;
  1328. auto update_tables = [&](auto code_point, auto& tables, auto& metadata, auto const& values) -> ErrorOr<void> {
  1329. static constexpr auto BLOCK_SIZE = CODE_POINT_TABLES_LSB_MASK + 1;
  1330. size_t unique_properties_index = 0;
  1331. if (auto block_index = tables.unique_properties.find_first_index(values); block_index.has_value()) {
  1332. unique_properties_index = *block_index;
  1333. } else {
  1334. unique_properties_index = tables.unique_properties.size();
  1335. TRY(tables.unique_properties.try_append(values));
  1336. }
  1337. TRY(metadata.current_block.try_append(unique_properties_index));
  1338. if (metadata.current_block.size() == BLOCK_SIZE || code_point == MAX_CODE_POINT) {
  1339. size_t stage2_index = 0;
  1340. if (auto block_index = metadata.unique_blocks.get(metadata.current_block); block_index.has_value()) {
  1341. stage2_index = *block_index;
  1342. } else {
  1343. stage2_index = tables.stage2.size();
  1344. TRY(tables.stage2.try_extend(metadata.current_block));
  1345. TRY(metadata.unique_blocks.try_set(metadata.current_block, stage2_index));
  1346. }
  1347. TRY(tables.stage1.try_append(stage2_index));
  1348. metadata.current_block.clear_with_capacity();
  1349. }
  1350. return {};
  1351. };
  1352. auto update_casing_tables = [&](auto code_point, auto& tables, auto& metadata) -> ErrorOr<void> {
  1353. CasingTable casing {};
  1354. while (metadata.iterator != metadata.end) {
  1355. if (code_point < metadata.iterator->code_point)
  1356. break;
  1357. if (code_point == metadata.iterator->code_point) {
  1358. casing = move(metadata.iterator->casing);
  1359. break;
  1360. }
  1361. ++metadata.iterator;
  1362. }
  1363. TRY(update_tables(code_point, tables, metadata, casing));
  1364. return {};
  1365. };
  1366. auto update_property_tables = [&](auto code_point, auto& tables, auto& metadata) -> ErrorOr<void> {
  1367. static Unicode::CodePointRangeComparator comparator {};
  1368. for (auto& property_values : metadata.property_values) {
  1369. size_t ranges_to_remove = 0;
  1370. auto has_property = false;
  1371. for (auto const& range : property_values) {
  1372. if (auto comparison = comparator(code_point, range); comparison <= 0) {
  1373. has_property = comparison == 0;
  1374. break;
  1375. }
  1376. ++ranges_to_remove;
  1377. }
  1378. metadata.property_set.unchecked_append(has_property);
  1379. property_values.remove(0, ranges_to_remove);
  1380. }
  1381. TRY(update_tables(code_point, tables, metadata, metadata.property_set));
  1382. metadata.property_set.clear_with_capacity();
  1383. return {};
  1384. };
  1385. CasingMetadata casing_metadata { unicode_data.code_point_data };
  1386. auto general_category_metadata = TRY(PropertyMetadata::create(unicode_data.general_categories));
  1387. auto property_metadata = TRY(PropertyMetadata::create(unicode_data.prop_list));
  1388. auto script_metadata = TRY(PropertyMetadata::create(unicode_data.script_list));
  1389. auto script_extension_metadata = TRY(PropertyMetadata::create(unicode_data.script_extensions));
  1390. auto grapheme_break_metadata = TRY(PropertyMetadata::create(unicode_data.grapheme_break_props));
  1391. auto word_break_metadata = TRY(PropertyMetadata::create(unicode_data.word_break_props));
  1392. auto sentence_break_metadata = TRY(PropertyMetadata::create(unicode_data.sentence_break_props));
  1393. for (u32 code_point = 0; code_point <= MAX_CODE_POINT; ++code_point) {
  1394. TRY(update_casing_tables(code_point, unicode_data.casing_tables, casing_metadata));
  1395. TRY(update_property_tables(code_point, unicode_data.general_category_tables, general_category_metadata));
  1396. TRY(update_property_tables(code_point, unicode_data.property_tables, property_metadata));
  1397. TRY(update_property_tables(code_point, unicode_data.script_tables, script_metadata));
  1398. TRY(update_property_tables(code_point, unicode_data.script_extension_tables, script_extension_metadata));
  1399. TRY(update_property_tables(code_point, unicode_data.grapheme_break_tables, grapheme_break_metadata));
  1400. TRY(update_property_tables(code_point, unicode_data.word_break_tables, word_break_metadata));
  1401. TRY(update_property_tables(code_point, unicode_data.sentence_break_tables, sentence_break_metadata));
  1402. }
  1403. return {};
  1404. }
  1405. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1406. {
  1407. StringView generated_header_path;
  1408. StringView generated_implementation_path;
  1409. StringView unicode_data_path;
  1410. StringView special_casing_path;
  1411. StringView case_folding_path;
  1412. StringView derived_general_category_path;
  1413. StringView prop_list_path;
  1414. StringView derived_core_prop_path;
  1415. StringView derived_binary_prop_path;
  1416. StringView prop_alias_path;
  1417. StringView prop_value_alias_path;
  1418. StringView name_alias_path;
  1419. StringView scripts_path;
  1420. StringView script_extensions_path;
  1421. StringView blocks_path;
  1422. StringView emoji_data_path;
  1423. StringView normalization_path;
  1424. StringView grapheme_break_path;
  1425. StringView word_break_path;
  1426. StringView sentence_break_path;
  1427. Core::ArgsParser args_parser;
  1428. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  1429. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  1430. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  1431. args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
  1432. args_parser.add_option(case_folding_path, "Path to CaseFolding.txt file", "case-folding-path", 'o', "case-folding-path");
  1433. args_parser.add_option(derived_general_category_path, "Path to DerivedGeneralCategory.txt file", "derived-general-category-path", 'g', "derived-general-category-path");
  1434. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  1435. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  1436. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  1437. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  1438. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  1439. args_parser.add_option(name_alias_path, "Path to NameAliases.txt file", "name-alias-path", 'm', "name-alias-path");
  1440. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  1441. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  1442. args_parser.add_option(blocks_path, "Path to Blocks.txt file", "blocks-path", 'k', "blocks-path");
  1443. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  1444. args_parser.add_option(normalization_path, "Path to DerivedNormalizationProps.txt file", "normalization-path", 'n', "normalization-path");
  1445. args_parser.add_option(grapheme_break_path, "Path to GraphemeBreakProperty.txt file", "grapheme-break-path", 'f', "grapheme-break-path");
  1446. args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path");
  1447. args_parser.add_option(sentence_break_path, "Path to SentenceBreakProperty.txt file", "sentence-break-path", 'i', "sentence-break-path");
  1448. args_parser.parse(arguments);
  1449. auto generated_header_file = TRY(open_file(generated_header_path, Core::File::OpenMode::Write));
  1450. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::File::OpenMode::Write));
  1451. auto unicode_data_file = TRY(open_file(unicode_data_path, Core::File::OpenMode::Read));
  1452. auto derived_general_category_file = TRY(open_file(derived_general_category_path, Core::File::OpenMode::Read));
  1453. auto special_casing_file = TRY(open_file(special_casing_path, Core::File::OpenMode::Read));
  1454. auto case_folding_file = TRY(open_file(case_folding_path, Core::File::OpenMode::Read));
  1455. auto prop_list_file = TRY(open_file(prop_list_path, Core::File::OpenMode::Read));
  1456. auto derived_core_prop_file = TRY(open_file(derived_core_prop_path, Core::File::OpenMode::Read));
  1457. auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path, Core::File::OpenMode::Read));
  1458. auto prop_alias_file = TRY(open_file(prop_alias_path, Core::File::OpenMode::Read));
  1459. auto prop_value_alias_file = TRY(open_file(prop_value_alias_path, Core::File::OpenMode::Read));
  1460. auto name_alias_file = TRY(open_file(name_alias_path, Core::File::OpenMode::Read));
  1461. auto scripts_file = TRY(open_file(scripts_path, Core::File::OpenMode::Read));
  1462. auto script_extensions_file = TRY(open_file(script_extensions_path, Core::File::OpenMode::Read));
  1463. auto blocks_file = TRY(open_file(blocks_path, Core::File::OpenMode::Read));
  1464. auto emoji_data_file = TRY(open_file(emoji_data_path, Core::File::OpenMode::Read));
  1465. auto normalization_file = TRY(open_file(normalization_path, Core::File::OpenMode::Read));
  1466. auto grapheme_break_file = TRY(open_file(grapheme_break_path, Core::File::OpenMode::Read));
  1467. auto word_break_file = TRY(open_file(word_break_path, Core::File::OpenMode::Read));
  1468. auto sentence_break_file = TRY(open_file(sentence_break_path, Core::File::OpenMode::Read));
  1469. UnicodeData unicode_data {};
  1470. TRY(parse_special_casing(*special_casing_file, unicode_data));
  1471. TRY(parse_case_folding(*case_folding_file, unicode_data));
  1472. TRY(parse_prop_list(*derived_general_category_file, unicode_data.general_categories));
  1473. TRY(parse_prop_list(*prop_list_file, unicode_data.prop_list));
  1474. TRY(parse_prop_list(*derived_core_prop_file, unicode_data.prop_list));
  1475. TRY(parse_prop_list(*derived_binary_prop_file, unicode_data.prop_list));
  1476. TRY(parse_prop_list(*emoji_data_file, unicode_data.prop_list));
  1477. TRY(parse_normalization_props(*normalization_file, unicode_data));
  1478. TRY(parse_alias_list(*prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases));
  1479. TRY(parse_prop_list(*scripts_file, unicode_data.script_list));
  1480. TRY(parse_prop_list(*script_extensions_file, unicode_data.script_extensions, true));
  1481. TRY(parse_block_display_names(*blocks_file, unicode_data));
  1482. TRY(parse_name_aliases(*name_alias_file, unicode_data));
  1483. TRY(parse_prop_list(*grapheme_break_file, unicode_data.grapheme_break_props));
  1484. TRY(parse_prop_list(*word_break_file, unicode_data.word_break_props));
  1485. TRY(parse_prop_list(*sentence_break_file, unicode_data.sentence_break_props));
  1486. populate_general_category_unions(unicode_data.general_categories);
  1487. TRY(parse_unicode_data(*unicode_data_file, unicode_data));
  1488. TRY(parse_value_alias_list(*prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases));
  1489. TRY(parse_value_alias_list(*prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false));
  1490. TRY(normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases));
  1491. TRY(create_code_point_tables(unicode_data));
  1492. TRY(generate_unicode_data_header(*generated_header_file, unicode_data));
  1493. TRY(generate_unicode_data_implementation(*generated_implementation_file, unicode_data));
  1494. return 0;
  1495. }