GenerateUnicodeData.cpp 74 KB

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