GenerateUnicodeData.cpp 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "GeneratorUtil.h"
  7. #include <AK/AllOf.h>
  8. #include <AK/Array.h>
  9. #include <AK/ByteString.h>
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/Error.h>
  12. #include <AK/Find.h>
  13. #include <AK/HashMap.h>
  14. #include <AK/Optional.h>
  15. #include <AK/QuickSort.h>
  16. #include <AK/SourceGenerator.h>
  17. #include <AK/StringUtils.h>
  18. #include <AK/Types.h>
  19. #include <AK/Vector.h>
  20. #include <LibCore/ArgsParser.h>
  21. #include <LibUnicode/CharacterTypes.h>
  22. // https://www.unicode.org/reports/tr44/#SpecialCasing.txt
  23. struct SpecialCasing {
  24. u32 index { 0 };
  25. u32 code_point { 0 };
  26. Vector<u32> lowercase_mapping;
  27. Vector<u32> uppercase_mapping;
  28. Vector<u32> titlecase_mapping;
  29. ByteString locale;
  30. ByteString condition;
  31. };
  32. // https://www.unicode.org/reports/tr44/#CaseFolding.txt
  33. struct CaseFolding {
  34. u32 code_point { 0 };
  35. StringView status { "Common"sv };
  36. Vector<u32> mapping { 0 };
  37. };
  38. // https://www.unicode.org/reports/tr44/#Character_Decomposition_Mappings
  39. struct CodePointDecomposition {
  40. // `tag` is a string since it's used for codegen as an enum value.
  41. ByteString 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<ByteString, 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<ByteString, 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. ByteString name;
  84. Optional<size_t> abbreviation;
  85. ByteString 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. ByteString unicode_1_name;
  92. ByteString 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. ByteString bidi_class;
  113. };
  114. struct CodePointComposition {
  115. u32 second_code_point { 0 };
  116. u32 combined_code_point { 0 };
  117. };
  118. struct UnicodeData {
  119. UniqueStringStorage unique_strings;
  120. u32 code_points_with_decomposition_mapping { 0 };
  121. Vector<u32> decomposition_mappings;
  122. HashMap<u32, Vector<CodePointComposition>> composition_mappings;
  123. Vector<ByteString> compatibility_tags;
  124. Vector<SpecialCasing> special_casing;
  125. u32 largest_special_casing_mapping_size { 0 };
  126. Vector<ByteString> conditions;
  127. Vector<ByteString> locales;
  128. Vector<CaseFolding> case_folding;
  129. u32 largest_case_folding_mapping_size { 0 };
  130. Vector<StringView> statuses;
  131. Vector<CodePointData> code_point_data;
  132. HashMap<u32, size_t> code_point_abbreviations;
  133. HashMap<u32, size_t> code_point_display_name_aliases;
  134. Vector<CodePointName> code_point_display_names;
  135. // https://www.unicode.org/reports/tr44/#General_Category_Values
  136. PropList general_categories;
  137. Vector<Alias> general_category_aliases;
  138. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  139. // any UCD file. Assigned code point ranges are derived as this generator is executed.
  140. // https://unicode.org/reports/tr18/#General_Category_Property
  141. PropList prop_list {
  142. { "Any"sv, { { 0, 0x10ffff } } },
  143. { "Assigned"sv, {} },
  144. { "ASCII"sv, { { 0, 0x7f } } },
  145. };
  146. Vector<Alias> prop_aliases;
  147. PropList script_list {
  148. { "Unknown"sv, {} },
  149. };
  150. Vector<Alias> script_aliases;
  151. PropList script_extensions;
  152. Vector<BlockName> block_display_names;
  153. // FIXME: We are not yet doing anything with this data. It will be needed for String.prototype.normalize.
  154. NormalizationProps normalization_props;
  155. PropList grapheme_break_props;
  156. PropList word_break_props;
  157. PropList sentence_break_props;
  158. CodePointTables<CasingTable> casing_tables;
  159. CodePointTables<PropertyTable> general_category_tables;
  160. CodePointTables<PropertyTable> property_tables;
  161. CodePointTables<PropertyTable> script_tables;
  162. CodePointTables<PropertyTable> script_extension_tables;
  163. CodePointTables<PropertyTable> grapheme_break_tables;
  164. CodePointTables<PropertyTable> word_break_tables;
  165. CodePointTables<PropertyTable> sentence_break_tables;
  166. HashTable<ByteString> bidirectional_classes;
  167. Vector<CodePointBidiClass> code_point_bidirectional_classes;
  168. };
  169. static ByteString sanitize_entry(ByteString const& entry)
  170. {
  171. auto sanitized = entry.replace("-"sv, "_"sv, ReplaceMode::All);
  172. sanitized = sanitized.replace(" "sv, "_"sv, ReplaceMode::All);
  173. StringBuilder builder;
  174. bool next_is_upper = true;
  175. for (auto ch : sanitized) {
  176. if (next_is_upper)
  177. builder.append_code_point(to_ascii_uppercase(ch));
  178. else
  179. builder.append_code_point(ch);
  180. next_is_upper = ch == '_';
  181. }
  182. return builder.to_byte_string();
  183. }
  184. static ErrorOr<void> parse_special_casing(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  185. {
  186. Array<u8, 1024> buffer;
  187. while (TRY(file.can_read_line())) {
  188. auto line = TRY(file.read_line(buffer));
  189. if (line.is_empty() || line.starts_with('#'))
  190. continue;
  191. if (auto index = line.find('#'); index.has_value())
  192. line = line.substring_view(0, *index);
  193. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  194. VERIFY(segments.size() == 5 || segments.size() == 6);
  195. SpecialCasing casing {};
  196. casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  197. casing.lowercase_mapping = parse_code_point_list(segments[1]);
  198. casing.titlecase_mapping = parse_code_point_list(segments[2]);
  199. casing.uppercase_mapping = parse_code_point_list(segments[3]);
  200. if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
  201. auto conditions = condition.split_view(' ', SplitBehavior::KeepEmpty);
  202. VERIFY(conditions.size() == 1 || conditions.size() == 2);
  203. if (conditions.size() == 2) {
  204. casing.locale = conditions[0];
  205. casing.condition = conditions[1];
  206. } else if (all_of(conditions[0], is_ascii_lower_alpha)) {
  207. casing.locale = conditions[0];
  208. } else {
  209. casing.condition = conditions[0];
  210. }
  211. if (!casing.locale.is_empty()) {
  212. casing.locale = ByteString::formatted("{:c}{}", to_ascii_uppercase(casing.locale[0]), casing.locale.substring_view(1));
  213. if (!unicode_data.locales.contains_slow(casing.locale))
  214. unicode_data.locales.append(casing.locale);
  215. }
  216. casing.condition = casing.condition.replace("_"sv, ""sv, ReplaceMode::All);
  217. if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
  218. unicode_data.conditions.append(casing.condition);
  219. }
  220. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.lowercase_mapping.size());
  221. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.titlecase_mapping.size());
  222. unicode_data.largest_special_casing_mapping_size = max(unicode_data.largest_special_casing_mapping_size, casing.uppercase_mapping.size());
  223. unicode_data.special_casing.append(move(casing));
  224. }
  225. quick_sort(unicode_data.special_casing, [](auto const& lhs, auto const& rhs) {
  226. if (lhs.code_point != rhs.code_point)
  227. return lhs.code_point < rhs.code_point;
  228. if (lhs.locale.is_empty() && !rhs.locale.is_empty())
  229. return false;
  230. if (!lhs.locale.is_empty() && rhs.locale.is_empty())
  231. return true;
  232. return lhs.locale < rhs.locale;
  233. });
  234. for (u32 i = 0; i < unicode_data.special_casing.size(); ++i)
  235. unicode_data.special_casing[i].index = i;
  236. return {};
  237. }
  238. static ErrorOr<void> parse_case_folding(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  239. {
  240. Array<u8, 1024> buffer;
  241. while (TRY(file.can_read_line())) {
  242. auto line = TRY(file.read_line(buffer));
  243. if (line.is_empty() || line.starts_with('#'))
  244. continue;
  245. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  246. VERIFY(segments.size() == 4);
  247. CaseFolding folding {};
  248. folding.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  249. folding.mapping = parse_code_point_list(segments[2]);
  250. switch (segments[1].trim_whitespace()[0]) {
  251. case 'C':
  252. folding.status = "Common"sv;
  253. break;
  254. case 'F':
  255. folding.status = "Full"sv;
  256. break;
  257. case 'S':
  258. folding.status = "Simple"sv;
  259. break;
  260. case 'T':
  261. folding.status = "Special"sv;
  262. break;
  263. }
  264. unicode_data.largest_case_folding_mapping_size = max(unicode_data.largest_case_folding_mapping_size, folding.mapping.size());
  265. if (!unicode_data.statuses.contains_slow(folding.status))
  266. unicode_data.statuses.append(folding.status);
  267. unicode_data.case_folding.append(move(folding));
  268. }
  269. quick_sort(unicode_data.case_folding, [](auto const& lhs, auto const& rhs) {
  270. if (lhs.code_point != rhs.code_point)
  271. return lhs.code_point < rhs.code_point;
  272. return lhs.status < rhs.status;
  273. });
  274. return {};
  275. }
  276. static ErrorOr<void> parse_prop_list(Core::InputBufferedFile& file, PropList& prop_list, bool multi_value_property = false, bool sanitize_property = false)
  277. {
  278. Array<u8, 1024> buffer;
  279. while (TRY(file.can_read_line())) {
  280. auto line = TRY(file.read_line(buffer));
  281. if (line.is_empty() || line.starts_with('#'))
  282. continue;
  283. if (auto index = line.find('#'); index.has_value())
  284. line = line.substring_view(0, *index);
  285. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  286. VERIFY(segments.size() == 2 || segments.size() == 3);
  287. String combined_segment_buffer;
  288. if (segments.size() == 3) {
  289. // For example, in DerivedCoreProperties.txt, there are lines such as:
  290. //
  291. // 094D ; InCB; Linker # Mn DEVANAGARI SIGN VIRAMA
  292. //
  293. // These are used in text segmentation to prevent breaking within some extended grapheme clusters.
  294. // So here, we combine the segments into a single property, which allows us to simply do code point
  295. // property lookups at runtime for specific Indic Conjunct Break sequences.
  296. combined_segment_buffer = MUST(String::join('_', Array { segments[1].trim_whitespace(), segments[2].trim_whitespace() }));
  297. segments[1] = combined_segment_buffer;
  298. }
  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() : ByteString { 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. ByteString 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<ByteString> 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) : ByteString { alias }, value);
  398. if (segments.size() == 4) {
  399. alias = segments[3].trim_whitespace();
  400. append_alias(sanitize_alias ? sanitize_entry(alias) : ByteString { 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_byte_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 = ByteString::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 void add_composition_mapping(u32 code_point, CodePointDecomposition& decomposition, UnicodeData& unicode_data, Vector<Unicode::CodePointRange> const& full_composition_exclusion_code_points)
  510. {
  511. if (decomposition.decomposition_size != 2)
  512. return;
  513. if (decomposition.tag != "Canonical"sv)
  514. return;
  515. static Unicode::CodePointRangeComparator comparator {};
  516. for (auto const& range : full_composition_exclusion_code_points) {
  517. auto comparison = comparator(code_point, range);
  518. if (comparison == 0)
  519. return;
  520. if (comparison < 0)
  521. break;
  522. }
  523. u32 const first_code_point = unicode_data.decomposition_mappings[decomposition.decomposition_index];
  524. u32 const second_code_point = unicode_data.decomposition_mappings[decomposition.decomposition_index + 1];
  525. unicode_data.composition_mappings.ensure(first_code_point).append(CodePointComposition { .second_code_point = second_code_point, .combined_code_point = code_point });
  526. }
  527. static ErrorOr<void> parse_block_display_names(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  528. {
  529. Array<u8, 1024> buffer;
  530. while (TRY(file.can_read_line())) {
  531. auto line = TRY(file.read_line(buffer));
  532. if (line.is_empty() || line.starts_with('#'))
  533. continue;
  534. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  535. VERIFY(segments.size() == 2);
  536. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  537. auto display_name = segments[1].trim_whitespace();
  538. auto index = unicode_data.unique_strings.ensure(display_name);
  539. unicode_data.block_display_names.append({ code_point_range, index });
  540. }
  541. TRY(file.seek(0, SeekMode::SetPosition));
  542. return {};
  543. }
  544. static ErrorOr<void> parse_unicode_data(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  545. {
  546. Optional<u32> code_point_range_start;
  547. auto& assigned_code_points = unicode_data.prop_list.find("Assigned"sv)->value;
  548. auto const& full_composition_exclusion_code_points = unicode_data.prop_list.find("Full_Composition_Exclusion"sv)->value;
  549. Optional<u32> assigned_code_point_range_start = 0;
  550. u32 previous_code_point = 0;
  551. Array<u8, 1024> buffer;
  552. while (TRY(file.can_read_line())) {
  553. auto line = TRY(file.read_line(buffer));
  554. if (line.is_empty())
  555. continue;
  556. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  557. VERIFY(segments.size() == 15);
  558. CodePointData data {};
  559. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  560. data.name = segments[1];
  561. data.casing.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
  562. data.bidi_class = segments[4];
  563. data.decomposition_mapping = parse_decomposition_mapping(segments[5], unicode_data);
  564. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  565. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  566. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  567. data.bidi_mirrored = segments[9] == "Y"sv;
  568. data.unicode_1_name = segments[10];
  569. data.iso_comment = segments[11];
  570. data.casing.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
  571. data.casing.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
  572. data.casing.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
  573. if (auto abbreviation = unicode_data.code_point_abbreviations.get(data.code_point); abbreviation.has_value())
  574. data.abbreviation = *abbreviation;
  575. if (!assigned_code_point_range_start.has_value())
  576. assigned_code_point_range_start = data.code_point;
  577. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>"sv)) {
  578. VERIFY(!code_point_range_start.has_value() && assigned_code_point_range_start.has_value());
  579. code_point_range_start = data.code_point;
  580. data.name = data.name.substring(1, data.name.length() - 9);
  581. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  582. assigned_code_point_range_start.clear();
  583. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>"sv)) {
  584. VERIFY(code_point_range_start.has_value());
  585. Unicode::CodePointRange code_point_range { *code_point_range_start, data.code_point };
  586. assigned_code_points.append(code_point_range);
  587. data.name = data.name.substring(1, data.name.length() - 8);
  588. code_point_range_start.clear();
  589. add_canonical_code_point_name(code_point_range, data.name, unicode_data);
  590. unicode_data.code_point_bidirectional_classes.append({ code_point_range, data.bidi_class });
  591. } else {
  592. add_canonical_code_point_name({ data.code_point, data.code_point }, data.name, unicode_data);
  593. unicode_data.code_point_bidirectional_classes.append({ { data.code_point, data.code_point }, data.bidi_class });
  594. if ((data.code_point > 0) && (data.code_point - previous_code_point) != 1) {
  595. VERIFY(assigned_code_point_range_start.has_value());
  596. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  597. assigned_code_point_range_start = data.code_point;
  598. }
  599. }
  600. for (auto const& casing : unicode_data.special_casing) {
  601. if (casing.code_point == data.code_point)
  602. data.casing.special_casing_indices.append(casing.index);
  603. }
  604. for (size_t i = 0; i < unicode_data.case_folding.size(); ++i) {
  605. if (auto const& folding = unicode_data.case_folding[i]; folding.code_point == data.code_point)
  606. data.casing.case_folding_indices.append(i);
  607. }
  608. unicode_data.code_points_with_decomposition_mapping += data.decomposition_mapping.has_value();
  609. if (data.decomposition_mapping.has_value())
  610. add_composition_mapping(data.code_point, *data.decomposition_mapping, unicode_data, full_composition_exclusion_code_points);
  611. unicode_data.bidirectional_classes.set(data.bidi_class, AK::HashSetExistingEntryBehavior::Keep);
  612. previous_code_point = data.code_point;
  613. unicode_data.code_point_data.append(move(data));
  614. }
  615. return {};
  616. }
  617. static ErrorOr<void> generate_unicode_data_header(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  618. {
  619. StringBuilder builder;
  620. SourceGenerator generator { builder };
  621. generator.set("special_casing_mapping_size", ByteString::number(unicode_data.largest_special_casing_mapping_size));
  622. generator.set("case_folding_mapping_size", ByteString::number(unicode_data.largest_case_folding_mapping_size));
  623. auto generate_enum = [&](StringView name, StringView default_, auto values, Vector<Alias> aliases = {}) {
  624. quick_sort(values);
  625. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  626. generator.set("name", name);
  627. generator.set("underlying", ByteString::formatted("{}UnderlyingType", name));
  628. generator.set("type", ((values.size() + !default_.is_empty()) < 256) ? "u8"sv : "u16"sv);
  629. generator.append(R"~~~(
  630. using @underlying@ = @type@;
  631. enum class @name@ : @underlying@ {)~~~");
  632. if (!default_.is_empty()) {
  633. generator.set("default", default_);
  634. generator.append(R"~~~(
  635. @default@,)~~~");
  636. }
  637. for (auto const& value : values) {
  638. generator.set("value", value);
  639. generator.append(R"~~~(
  640. @value@,)~~~");
  641. }
  642. for (auto const& alias : aliases) {
  643. generator.set("alias", alias.alias);
  644. generator.set("value", alias.name);
  645. generator.append(R"~~~(
  646. @alias@ = @value@,)~~~");
  647. }
  648. generator.append(R"~~~(
  649. };
  650. )~~~");
  651. };
  652. generator.append(R"~~~(
  653. #pragma once
  654. #include <AK/Types.h>
  655. #include <LibUnicode/Forward.h>
  656. namespace Unicode {
  657. )~~~");
  658. generate_enum("Locale"sv, "None"sv, unicode_data.locales);
  659. generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
  660. generate_enum("CaseFoldingStatus"sv, {}, move(unicode_data.statuses));
  661. generate_enum("GeneralCategory"sv, {}, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  662. generate_enum("Property"sv, {}, unicode_data.prop_list.keys(), unicode_data.prop_aliases);
  663. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), unicode_data.script_aliases);
  664. generate_enum("GraphemeBreakProperty"sv, {}, unicode_data.grapheme_break_props.keys());
  665. generate_enum("WordBreakProperty"sv, {}, unicode_data.word_break_props.keys());
  666. generate_enum("SentenceBreakProperty"sv, {}, unicode_data.sentence_break_props.keys());
  667. generate_enum("CompatibilityFormattingTag"sv, "Canonical"sv, unicode_data.compatibility_tags);
  668. generate_enum("BidirectionalClass"sv, {}, unicode_data.bidirectional_classes.values());
  669. generator.append(R"~~~(
  670. struct SpecialCasing {
  671. u32 code_point { 0 };
  672. u32 lowercase_mapping[@special_casing_mapping_size@];
  673. u32 lowercase_mapping_size { 0 };
  674. u32 uppercase_mapping[@special_casing_mapping_size@];
  675. u32 uppercase_mapping_size { 0 };
  676. u32 titlecase_mapping[@special_casing_mapping_size@];
  677. u32 titlecase_mapping_size { 0 };
  678. Locale locale { Locale::None };
  679. Condition condition { Condition::None };
  680. };
  681. struct CaseFolding {
  682. u32 code_point { 0 };
  683. CaseFoldingStatus status { CaseFoldingStatus::Common };
  684. u32 mapping[@case_folding_mapping_size@];
  685. u32 mapping_size { 0 };
  686. };
  687. struct CodePointDecompositionRaw {
  688. u32 code_point { 0 };
  689. CompatibilityFormattingTag tag { CompatibilityFormattingTag::Canonical };
  690. size_t decomposition_index { 0 };
  691. size_t decomposition_count { 0 };
  692. };
  693. struct CodePointDecomposition {
  694. u32 code_point { 0 };
  695. CompatibilityFormattingTag tag { CompatibilityFormattingTag::Canonical };
  696. ReadonlySpan<u32> decomposition;
  697. };
  698. struct CodePointCompositionRaw {
  699. u32 code_point { 0 };
  700. u32 second_code_point { 0 };
  701. u32 combined_code_point { 0 };
  702. };
  703. Optional<Locale> locale_from_string(StringView locale);
  704. ReadonlySpan<SpecialCasing> special_case_mapping(u32 code_point);
  705. ReadonlySpan<CaseFolding> case_folding_mapping(u32 code_point);
  706. }
  707. )~~~");
  708. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  709. return {};
  710. }
  711. static ErrorOr<void> generate_unicode_data_implementation(Core::InputBufferedFile& file, UnicodeData const& unicode_data)
  712. {
  713. StringBuilder builder;
  714. SourceGenerator generator { builder };
  715. generator.set("string_index_type"sv, unicode_data.unique_strings.type_that_fits());
  716. generator.set("special_casing_size", ByteString::number(unicode_data.special_casing.size()));
  717. generator.set("case_folding_size", ByteString::number(unicode_data.case_folding.size()));
  718. generator.set("CODE_POINT_TABLES_LSB_COUNT", TRY(String::number(CODE_POINT_TABLES_LSB_COUNT)));
  719. generator.set("CODE_POINT_TABLES_LSB_MASK", TRY(String::formatted("{:#x}", CODE_POINT_TABLES_LSB_MASK)));
  720. generator.append(R"~~~(
  721. #include <AK/Array.h>
  722. #include <AK/BinarySearch.h>
  723. #include <AK/CharacterTypes.h>
  724. #include <AK/Optional.h>
  725. #include <AK/Span.h>
  726. #include <AK/ByteString.h>
  727. #include <AK/StringView.h>
  728. #include <LibUnicode/CharacterTypes.h>
  729. #include <LibUnicode/UnicodeData.h>
  730. #include <LibUnicode/Normalize.h>
  731. namespace Unicode {
  732. )~~~");
  733. unicode_data.unique_strings.generate(generator);
  734. auto append_list_and_size = [&](auto const& list, StringView format) {
  735. if (list.is_empty()) {
  736. generator.append(", {}, 0");
  737. return;
  738. }
  739. bool first = true;
  740. generator.append(", {");
  741. for (auto const& item : list) {
  742. generator.append(first ? " "sv : ", "sv);
  743. generator.append(ByteString::formatted(format, item));
  744. first = false;
  745. }
  746. generator.append(ByteString::formatted(" }}, {}", list.size()));
  747. };
  748. generator.append(R"~~~(
  749. static constexpr Array<SpecialCasing, @special_casing_size@> s_special_case { {)~~~");
  750. for (auto const& casing : unicode_data.special_casing) {
  751. generator.set("code_point", ByteString::formatted("{:#x}", casing.code_point));
  752. generator.append(R"~~~(
  753. { @code_point@)~~~");
  754. constexpr auto format = "{:#x}"sv;
  755. append_list_and_size(casing.lowercase_mapping, format);
  756. append_list_and_size(casing.uppercase_mapping, format);
  757. append_list_and_size(casing.titlecase_mapping, format);
  758. generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
  759. generator.append(", Locale::@locale@");
  760. generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
  761. generator.append(", Condition::@condition@");
  762. generator.append(" },");
  763. }
  764. generator.append(R"~~~(
  765. } };
  766. static constexpr Array<CaseFolding, @case_folding_size@> s_case_folding { {)~~~");
  767. for (auto const& folding : unicode_data.case_folding) {
  768. generator.set("code_point", ByteString::formatted("{:#x}", folding.code_point));
  769. generator.set("status", folding.status);
  770. generator.append(R"~~~(
  771. { @code_point@, CaseFoldingStatus::@status@)~~~");
  772. append_list_and_size(folding.mapping, "{:#x}"sv);
  773. generator.append(" },");
  774. }
  775. generator.append(R"~~~(
  776. } };
  777. struct CasingTable {
  778. u8 canonical_combining_class { 0 };
  779. i32 simple_uppercase_mapping { -1 };
  780. i32 simple_lowercase_mapping { -1 };
  781. i32 simple_titlecase_mapping { -1 };
  782. u32 special_casing_start_index { 0 };
  783. u32 special_casing_size { 0 };
  784. u32 case_folding_start_index { 0 };
  785. u32 case_folding_size { 0 };
  786. };
  787. struct CodePointAbbreviation {
  788. u32 code_point { 0 };
  789. @string_index_type@ abbreviation { 0 };
  790. };
  791. template<typename MappingType>
  792. struct CodePointComparator {
  793. constexpr int operator()(u32 code_point, MappingType const& mapping)
  794. {
  795. return code_point - mapping.code_point;
  796. }
  797. };
  798. struct BlockNameData {
  799. CodePointRange code_point_range {};
  800. @string_index_type@ display_name { 0 };
  801. };
  802. struct BlockNameComparator : public CodePointRangeComparator {
  803. constexpr int operator()(u32 code_point, BlockNameData const& name)
  804. {
  805. return CodePointRangeComparator::operator()(code_point, name.code_point_range);
  806. }
  807. };
  808. struct CodePointName {
  809. CodePointRange code_point_range {};
  810. @string_index_type@ display_name { 0 };
  811. };
  812. struct CodePointNameComparator : public CodePointRangeComparator {
  813. constexpr int operator()(u32 code_point, CodePointName const& name)
  814. {
  815. return CodePointRangeComparator::operator()(code_point, name.code_point_range);
  816. }
  817. };
  818. struct BidiClassData {
  819. CodePointRange code_point_range {};
  820. BidirectionalClass bidi_class {};
  821. };
  822. struct CodePointBidiClassComparator : public CodePointRangeComparator {
  823. constexpr int operator()(u32 code_point, BidiClassData const& bidi_class)
  824. {
  825. return CodePointRangeComparator::operator()(code_point, bidi_class.code_point_range);
  826. }
  827. };
  828. )~~~");
  829. generator.set("decomposition_mappings_size", ByteString::number(unicode_data.decomposition_mappings.size()));
  830. generator.append("\nstatic constexpr Array<u32, @decomposition_mappings_size@> s_decomposition_mappings_data { ");
  831. generator.append(ByteString::join(", "sv, unicode_data.decomposition_mappings, "{:#x}"sv));
  832. generator.append(" };\n");
  833. auto append_code_point_mappings = [&](StringView name, StringView mapping_type, u32 size, auto mapping_getter) {
  834. generator.set("name", name);
  835. generator.set("mapping_type", mapping_type);
  836. generator.set("size", ByteString::number(size));
  837. generator.append(R"~~~(
  838. static constexpr Array<@mapping_type@, @size@> s_@name@_mappings { {
  839. )~~~");
  840. constexpr size_t max_mappings_per_row = 20;
  841. size_t mappings_in_current_row = 0;
  842. for (auto const& data : unicode_data.code_point_data) {
  843. auto mapping = mapping_getter(data);
  844. if constexpr (requires { mapping.has_value(); }) {
  845. if (!mapping.has_value())
  846. continue;
  847. } else {
  848. if (mapping.is_empty())
  849. continue;
  850. }
  851. if (mappings_in_current_row++ > 0)
  852. generator.append(" ");
  853. generator.set("code_point", ByteString::formatted("{:#x}", data.code_point));
  854. generator.append("{ @code_point@");
  855. if constexpr (IsSame<decltype(mapping), Optional<u32>> || IsSame<decltype(mapping), Optional<size_t>>) {
  856. generator.set("mapping", ByteString::formatted("{:#x}", *mapping));
  857. generator.append(", @mapping@ },");
  858. } else if constexpr (IsSame<decltype(mapping), Optional<CodePointDecomposition>>) {
  859. generator.set("tag", mapping->tag);
  860. generator.set("start", ByteString::number(mapping->decomposition_index));
  861. generator.set("size", ByteString::number(mapping->decomposition_size));
  862. generator.append(", CompatibilityFormattingTag::@tag@, @start@, @size@ },");
  863. } else {
  864. append_list_and_size(mapping, "&s_@name@[{}]"sv);
  865. generator.append(" },");
  866. }
  867. if (mappings_in_current_row == max_mappings_per_row) {
  868. mappings_in_current_row = 0;
  869. generator.append("\n ");
  870. }
  871. }
  872. generator.append(R"~~~(
  873. } };
  874. )~~~");
  875. };
  876. append_code_point_mappings("abbreviation"sv, "CodePointAbbreviation"sv, unicode_data.code_point_abbreviations.size(), [](auto const& data) { return data.abbreviation; });
  877. append_code_point_mappings("decomposition"sv, "CodePointDecompositionRaw"sv, unicode_data.code_points_with_decomposition_mapping, [](auto const& data) { return data.decomposition_mapping; });
  878. size_t composition_mappings_size = 0;
  879. for (auto const& entry : unicode_data.composition_mappings)
  880. composition_mappings_size += entry.value.size();
  881. generator.set("composition_mappings_size", ByteString::number(composition_mappings_size));
  882. generator.append(R"~~~(
  883. static constexpr Array<CodePointCompositionRaw, @composition_mappings_size@> s_composition_mappings { {
  884. )~~~");
  885. constexpr size_t max_mappings_per_row = 40;
  886. size_t mappings_in_current_row = 0;
  887. auto first_code_points = unicode_data.composition_mappings.keys();
  888. quick_sort(first_code_points);
  889. for (auto const first_code_point : first_code_points) {
  890. for (auto const& mapping : unicode_data.composition_mappings.find(first_code_point)->value) {
  891. if (mappings_in_current_row++ > 0)
  892. generator.append(" ");
  893. generator.set("code_point", ByteString::formatted("{:#x}", first_code_point));
  894. generator.set("second_code_point", ByteString::formatted("{:#x}", mapping.second_code_point));
  895. generator.set("combined_code_point", ByteString::formatted("{:#x}", mapping.combined_code_point));
  896. generator.append("{ @code_point@, @second_code_point@, @combined_code_point@ },");
  897. if (mappings_in_current_row == max_mappings_per_row) {
  898. mappings_in_current_row = 0;
  899. generator.append("\n ");
  900. }
  901. }
  902. }
  903. generator.append(R"~~~(
  904. } };
  905. )~~~");
  906. auto append_casing_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  907. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  908. generator.set("size", TRY(String::number(unique_properties.size())));
  909. auto optional_code_point_to_string = [](auto const& code_point) -> ErrorOr<String> {
  910. if (!code_point.has_value())
  911. return "-1"_string;
  912. return String::number(*code_point);
  913. };
  914. auto first_index_to_string = [](auto const& list) -> ErrorOr<String> {
  915. if (list.is_empty())
  916. return "0"_string;
  917. return String::number(list.first());
  918. };
  919. generator.append(R"~~~(
  920. static constexpr Array<CasingTable, @size@> @name@ { {)~~~");
  921. for (auto const& casing : unique_properties) {
  922. generator.set("canonical_combining_class", TRY(String::number(casing.canonical_combining_class)));
  923. generator.set("simple_uppercase_mapping", TRY(optional_code_point_to_string(casing.simple_uppercase_mapping)));
  924. generator.set("simple_lowercase_mapping", TRY(optional_code_point_to_string(casing.simple_lowercase_mapping)));
  925. generator.set("simple_titlecase_mapping", TRY(optional_code_point_to_string(casing.simple_titlecase_mapping)));
  926. generator.set("special_casing_start_index", TRY(first_index_to_string(casing.special_casing_indices)));
  927. generator.set("special_casing_size", TRY(String::number(casing.special_casing_indices.size())));
  928. generator.set("case_folding_start_index", TRY(first_index_to_string(casing.case_folding_indices)));
  929. generator.set("case_folding_size", TRY(String::number(casing.case_folding_indices.size())));
  930. generator.append(R"~~~(
  931. { @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@ },)~~~");
  932. }
  933. generator.append(R"~~~(
  934. } };
  935. )~~~");
  936. return {};
  937. };
  938. auto append_property_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  939. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  940. generator.set("outer_size", TRY(String::number(unique_properties.size())));
  941. generator.set("inner_size", TRY(String::number(unique_properties[0].size())));
  942. generator.append(R"~~~(
  943. static constexpr Array<Array<bool, @inner_size@>, @outer_size@> @name@ { {)~~~");
  944. for (auto const& property_set : unique_properties) {
  945. generator.append(R"~~~(
  946. { )~~~");
  947. for (auto value : property_set) {
  948. generator.set("value", TRY(String::formatted("{}", value)));
  949. generator.append("@value@, ");
  950. }
  951. generator.append(" },");
  952. }
  953. generator.append(R"~~~(
  954. } };
  955. )~~~");
  956. return {};
  957. };
  958. auto append_code_point_tables = [&](StringView collection_snake, auto const& tables, auto& append_unique_properties) -> ErrorOr<void> {
  959. auto append_stage = [&](auto const& stage, auto name, auto type) -> ErrorOr<void> {
  960. generator.set("name", TRY(String::formatted("{}_{}", collection_snake, name)));
  961. generator.set("size", TRY(String::number(stage.size())));
  962. generator.set("type", type);
  963. generator.append(R"~~~(
  964. static constexpr Array<@type@, @size@> @name@ { {
  965. )~~~");
  966. static constexpr size_t max_values_per_row = 300;
  967. size_t values_in_current_row = 0;
  968. for (auto value : stage) {
  969. if (values_in_current_row++ > 0)
  970. generator.append(", ");
  971. generator.set("value", TRY(String::number(value)));
  972. generator.append("@value@");
  973. if (values_in_current_row == max_values_per_row) {
  974. values_in_current_row = 0;
  975. generator.append(",\n ");
  976. }
  977. }
  978. generator.append(R"~~~(
  979. } };
  980. )~~~");
  981. return {};
  982. };
  983. TRY(append_stage(tables.stage1, "stage1"sv, "u16"sv));
  984. TRY(append_stage(tables.stage2, "stage2"sv, "u16"sv));
  985. TRY(append_unique_properties(collection_snake, tables.unique_properties));
  986. return {};
  987. };
  988. TRY(append_code_point_tables("s_casings"sv, unicode_data.casing_tables, append_casing_table));
  989. TRY(append_code_point_tables("s_general_categories"sv, unicode_data.general_category_tables, append_property_table));
  990. TRY(append_code_point_tables("s_properties"sv, unicode_data.property_tables, append_property_table));
  991. TRY(append_code_point_tables("s_scripts"sv, unicode_data.script_tables, append_property_table));
  992. TRY(append_code_point_tables("s_script_extensions"sv, unicode_data.script_extension_tables, append_property_table));
  993. TRY(append_code_point_tables("s_grapheme_break_properties"sv, unicode_data.grapheme_break_tables, append_property_table));
  994. TRY(append_code_point_tables("s_word_break_properties"sv, unicode_data.word_break_tables, append_property_table));
  995. TRY(append_code_point_tables("s_sentence_break_properties"sv, unicode_data.sentence_break_tables, append_property_table));
  996. auto append_code_point_display_names = [&](StringView type, StringView name, auto const& display_names) {
  997. constexpr size_t max_values_per_row = 30;
  998. size_t values_in_current_row = 0;
  999. generator.set("type", type);
  1000. generator.set("name", name);
  1001. generator.set("size", ByteString::number(display_names.size()));
  1002. generator.append(R"~~~(
  1003. static constexpr Array<@type@, @size@> @name@ { {
  1004. )~~~");
  1005. for (auto const& display_name : display_names) {
  1006. if (values_in_current_row++ > 0)
  1007. generator.append(", ");
  1008. generator.set("first", ByteString::formatted("{:#x}", display_name.code_point_range.first));
  1009. generator.set("last", ByteString::formatted("{:#x}", display_name.code_point_range.last));
  1010. generator.set("name", ByteString::number(display_name.name));
  1011. generator.append("{ { @first@, @last@ }, @name@ }");
  1012. if (values_in_current_row == max_values_per_row) {
  1013. values_in_current_row = 0;
  1014. generator.append(",\n ");
  1015. }
  1016. }
  1017. generator.append(R"~~~(
  1018. } };
  1019. )~~~");
  1020. };
  1021. append_code_point_display_names("BlockNameData"sv, "s_block_display_names"sv, unicode_data.block_display_names);
  1022. append_code_point_display_names("CodePointName"sv, "s_code_point_display_names"sv, unicode_data.code_point_display_names);
  1023. {
  1024. constexpr size_t max_bidi_classes_per_row = 20;
  1025. size_t bidi_classes_in_current_row = 0;
  1026. generator.set("size"sv, ByteString::number(unicode_data.code_point_bidirectional_classes.size()));
  1027. generator.append(R"~~~(
  1028. static constexpr Array<BidiClassData, @size@> s_bidirectional_classes { {
  1029. )~~~");
  1030. for (auto const& data : unicode_data.code_point_bidirectional_classes) {
  1031. if (bidi_classes_in_current_row++ > 0)
  1032. generator.append(", ");
  1033. generator.set("first", ByteString::formatted("{:#x}", data.code_point_range.first));
  1034. generator.set("last", ByteString::formatted("{:#x}", data.code_point_range.last));
  1035. generator.set("bidi_class", data.bidi_class);
  1036. generator.append("{ { @first@, @last@ }, BidirectionalClass::@bidi_class@ }");
  1037. if (bidi_classes_in_current_row == max_bidi_classes_per_row) {
  1038. bidi_classes_in_current_row = 0;
  1039. generator.append(",\n ");
  1040. }
  1041. }
  1042. generator.append(R"~~~(
  1043. } };
  1044. )~~~");
  1045. }
  1046. generator.append(R"~~~(
  1047. Optional<StringView> code_point_block_display_name(u32 code_point)
  1048. {
  1049. if (auto const* entry = binary_search(s_block_display_names, code_point, nullptr, BlockNameComparator {}))
  1050. return decode_string(entry->display_name);
  1051. return {};
  1052. }
  1053. ReadonlySpan<BlockName> block_display_names()
  1054. {
  1055. static auto display_names = []() {
  1056. Array<BlockName, s_block_display_names.size()> display_names;
  1057. for (size_t i = 0; i < s_block_display_names.size(); ++i) {
  1058. auto const& display_name = s_block_display_names[i];
  1059. display_names[i] = { display_name.code_point_range, decode_string(display_name.display_name) };
  1060. }
  1061. return display_names;
  1062. }();
  1063. return display_names.span();
  1064. }
  1065. Optional<ByteString> code_point_display_name(u32 code_point)
  1066. {
  1067. if (auto const* entry = binary_search(s_code_point_display_names, code_point, nullptr, CodePointNameComparator {})) {
  1068. auto display_name = decode_string(entry->display_name);
  1069. if (display_name.ends_with("{:X}"sv))
  1070. return ByteString::formatted(display_name, code_point);
  1071. return display_name;
  1072. }
  1073. return {};
  1074. }
  1075. static CasingTable const& casing_table_for_code_point(u32 code_point)
  1076. {
  1077. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  1078. auto stage2_index = s_casings_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  1079. auto unique_properties_index = s_casings_stage2[stage2_index];
  1080. return s_casings_unique_properties[unique_properties_index];
  1081. }
  1082. )~~~");
  1083. auto append_code_point_mapping_search = [&](StringView method, StringView mapping, Optional<StringView> const& fallback = {}) {
  1084. generator.set("method", method);
  1085. generator.set("mapping", mapping);
  1086. generator.append(R"~~~(
  1087. u32 @method@(u32 code_point)
  1088. {
  1089. auto const& casing_table = casing_table_for_code_point(code_point);
  1090. auto mapping = casing_table.@mapping@;
  1091. )~~~");
  1092. if (fallback.has_value()) {
  1093. generator.set("fallback", *fallback);
  1094. generator.append(R"~~~(
  1095. return mapping == -1 ? @fallback@ : static_cast<u32>(mapping);)~~~");
  1096. } else {
  1097. generator.append(R"~~~(
  1098. return mapping;)~~~");
  1099. }
  1100. generator.append(R"~~~(
  1101. }
  1102. )~~~");
  1103. };
  1104. append_code_point_mapping_search("canonical_combining_class"sv, "canonical_combining_class"sv);
  1105. append_code_point_mapping_search("to_unicode_uppercase"sv, "simple_uppercase_mapping"sv, "code_point"sv);
  1106. append_code_point_mapping_search("to_unicode_lowercase"sv, "simple_lowercase_mapping"sv, "code_point"sv);
  1107. append_code_point_mapping_search("to_unicode_titlecase"sv, "simple_titlecase_mapping"sv, "code_point"sv);
  1108. generator.append(R"~~~(
  1109. ReadonlySpan<SpecialCasing> special_case_mapping(u32 code_point)
  1110. {
  1111. auto const& casing_table = casing_table_for_code_point(code_point);
  1112. if (casing_table.special_casing_size == 0)
  1113. return {};
  1114. return s_special_case.span().slice(casing_table.special_casing_start_index, casing_table.special_casing_size);
  1115. }
  1116. ReadonlySpan<CaseFolding> case_folding_mapping(u32 code_point)
  1117. {
  1118. auto const& casing_table = casing_table_for_code_point(code_point);
  1119. if (casing_table.case_folding_size == 0)
  1120. return {};
  1121. return s_case_folding.span().slice(casing_table.case_folding_start_index, casing_table.case_folding_size);
  1122. }
  1123. Optional<StringView> code_point_abbreviation(u32 code_point)
  1124. {
  1125. auto const* mapping = binary_search(s_abbreviation_mappings, code_point, nullptr, CodePointComparator<CodePointAbbreviation> {});
  1126. if (mapping == nullptr)
  1127. return {};
  1128. if (mapping->abbreviation == 0)
  1129. return {};
  1130. return decode_string(mapping->abbreviation);
  1131. }
  1132. Optional<CodePointDecomposition const> code_point_decomposition(u32 code_point)
  1133. {
  1134. auto const* mapping = binary_search(s_decomposition_mappings, code_point, nullptr, CodePointComparator<CodePointDecompositionRaw> {});
  1135. if (mapping == nullptr)
  1136. return {};
  1137. return CodePointDecomposition { mapping->code_point, mapping->tag, ReadonlySpan<u32> { s_decomposition_mappings_data.data() + mapping->decomposition_index, mapping->decomposition_count } };
  1138. }
  1139. Optional<u32> code_point_composition(u32 first_code_point, u32 second_code_point)
  1140. {
  1141. size_t mapping_index;
  1142. if (!binary_search(s_composition_mappings, first_code_point, &mapping_index, CodePointComparator<CodePointCompositionRaw> {}))
  1143. return {};
  1144. while (mapping_index > 0 && s_composition_mappings[mapping_index - 1].code_point == first_code_point)
  1145. mapping_index--;
  1146. for (; mapping_index < s_composition_mappings.size() && s_composition_mappings[mapping_index].code_point == first_code_point; ++mapping_index) {
  1147. if (s_composition_mappings[mapping_index].second_code_point == second_code_point)
  1148. return s_composition_mappings[mapping_index].combined_code_point;
  1149. }
  1150. return {};
  1151. }
  1152. Optional<BidirectionalClass> bidirectional_class(u32 code_point)
  1153. {
  1154. if (auto const* entry = binary_search(s_bidirectional_classes, code_point, nullptr, CodePointBidiClassComparator {}))
  1155. return entry->bidi_class;
  1156. return {};
  1157. }
  1158. )~~~");
  1159. auto append_prop_search = [&](StringView enum_title, StringView enum_snake, StringView collection_name) -> ErrorOr<void> {
  1160. generator.set("enum_title", enum_title);
  1161. generator.set("enum_snake", enum_snake);
  1162. generator.set("collection_name", collection_name);
  1163. generator.append(R"~~~(
  1164. bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@)
  1165. {
  1166. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  1167. auto stage2_index = @collection_name@_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  1168. auto unique_properties_index = @collection_name@_stage2[stage2_index];
  1169. auto const& property_set = @collection_name@_unique_properties[unique_properties_index];
  1170. return property_set[to_underlying(@enum_snake@)];
  1171. }
  1172. )~~~");
  1173. return {};
  1174. };
  1175. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& prop_list, Vector<Alias> const& aliases) -> ErrorOr<void> {
  1176. HashValueMap<StringView> hashes;
  1177. TRY(hashes.try_ensure_capacity(prop_list.size() + aliases.size()));
  1178. ValueFromStringOptions options {};
  1179. for (auto const& prop : prop_list) {
  1180. if constexpr (IsSame<RemoveCVReference<decltype(prop)>, ByteString>) {
  1181. hashes.set(CaseInsensitiveASCIIStringViewTraits::hash(prop), prop);
  1182. options.sensitivity = CaseSensitivity::CaseInsensitive;
  1183. } else {
  1184. hashes.set(prop.key.hash(), prop.key);
  1185. }
  1186. }
  1187. for (auto const& alias : aliases)
  1188. hashes.set(alias.alias.hash(), alias.alias);
  1189. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes), options);
  1190. return {};
  1191. };
  1192. TRY(append_from_string("Locale"sv, "locale"sv, unicode_data.locales, {}));
  1193. TRY(append_prop_search("GeneralCategory"sv, "general_category"sv, "s_general_categories"sv));
  1194. TRY(append_from_string("GeneralCategory"sv, "general_category"sv, unicode_data.general_categories, unicode_data.general_category_aliases));
  1195. TRY(append_prop_search("Property"sv, "property"sv, "s_properties"sv));
  1196. TRY(append_from_string("Property"sv, "property"sv, unicode_data.prop_list, unicode_data.prop_aliases));
  1197. TRY(append_prop_search("Script"sv, "script"sv, "s_scripts"sv));
  1198. TRY(append_prop_search("Script"sv, "script_extension"sv, "s_script_extensions"sv));
  1199. TRY(append_from_string("Script"sv, "script"sv, unicode_data.script_list, unicode_data.script_aliases));
  1200. TRY(append_prop_search("GraphemeBreakProperty"sv, "grapheme_break_property"sv, "s_grapheme_break_properties"sv));
  1201. TRY(append_prop_search("WordBreakProperty"sv, "word_break_property"sv, "s_word_break_properties"sv));
  1202. TRY(append_prop_search("SentenceBreakProperty"sv, "sentence_break_property"sv, "s_sentence_break_properties"sv));
  1203. TRY(append_from_string("BidirectionalClass"sv, "bidirectional_class"sv, unicode_data.bidirectional_classes, {}));
  1204. generator.append(R"~~~(
  1205. }
  1206. )~~~");
  1207. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  1208. return {};
  1209. }
  1210. static Vector<u32> flatten_code_point_ranges(Vector<Unicode::CodePointRange> const& code_points)
  1211. {
  1212. Vector<u32> flattened;
  1213. for (auto const& range : code_points) {
  1214. flattened.grow_capacity(range.last - range.first);
  1215. for (u32 code_point = range.first; code_point <= range.last; ++code_point)
  1216. flattened.append(code_point);
  1217. }
  1218. return flattened;
  1219. }
  1220. static Vector<Unicode::CodePointRange> form_code_point_ranges(Vector<u32> code_points)
  1221. {
  1222. Vector<Unicode::CodePointRange> ranges;
  1223. u32 range_start = code_points[0];
  1224. u32 range_end = range_start;
  1225. for (size_t i = 1; i < code_points.size(); ++i) {
  1226. u32 code_point = code_points[i];
  1227. if ((code_point - range_end) == 1) {
  1228. range_end = code_point;
  1229. } else {
  1230. ranges.append({ range_start, range_end });
  1231. range_start = code_point;
  1232. range_end = code_point;
  1233. }
  1234. }
  1235. ranges.append({ range_start, range_end });
  1236. return ranges;
  1237. }
  1238. static void sort_and_merge_code_point_ranges(Vector<Unicode::CodePointRange>& code_points)
  1239. {
  1240. quick_sort(code_points, [](auto const& range1, auto const& range2) {
  1241. return range1.first < range2.first;
  1242. });
  1243. for (size_t i = 0; i < code_points.size() - 1;) {
  1244. if (code_points[i].last >= code_points[i + 1].first) {
  1245. code_points[i].last = max(code_points[i].last, code_points[i + 1].last);
  1246. code_points.remove(i + 1);
  1247. } else {
  1248. ++i;
  1249. }
  1250. }
  1251. auto all_code_points = flatten_code_point_ranges(code_points);
  1252. code_points = form_code_point_ranges(all_code_points);
  1253. }
  1254. static void populate_general_category_unions(PropList& general_categories)
  1255. {
  1256. // The Unicode standard defines General Category values which are not in any UCD file. These
  1257. // values are simply unions of other values.
  1258. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  1259. auto populate_union = [&](auto alias, auto categories) {
  1260. auto& code_points = general_categories.ensure(alias);
  1261. for (auto const& category : categories)
  1262. code_points.extend(general_categories.find(category)->value);
  1263. sort_and_merge_code_point_ranges(code_points);
  1264. };
  1265. populate_union("LC"sv, Array { "Ll"sv, "Lu"sv, "Lt"sv });
  1266. populate_union("L"sv, Array { "Lu"sv, "Ll"sv, "Lt"sv, "Lm"sv, "Lo"sv });
  1267. populate_union("M"sv, Array { "Mn"sv, "Mc"sv, "Me"sv });
  1268. populate_union("N"sv, Array { "Nd"sv, "Nl"sv, "No"sv });
  1269. populate_union("P"sv, Array { "Pc"sv, "Pd"sv, "Ps"sv, "Pe"sv, "Pi"sv, "Pf"sv, "Po"sv });
  1270. populate_union("S"sv, Array { "Sm"sv, "Sc"sv, "Sk"sv, "So"sv });
  1271. populate_union("Z"sv, Array { "Zs"sv, "Zl"sv, "Zp"sv });
  1272. populate_union("C"sv, Array { "Cc"sv, "Cf"sv, "Cs"sv, "Co"sv, "Cn"sv });
  1273. }
  1274. static ErrorOr<void> normalize_script_extensions(PropList& script_extensions, PropList const& script_list, Vector<Alias> const& script_aliases)
  1275. {
  1276. // The ScriptExtensions UCD file lays out its code point ranges rather uniquely compared to
  1277. // other files. The Script listed on each line may either be a full Script string or an aliased
  1278. // abbreviation. Further, the extensions may or may not include the base Script list. Normalize
  1279. // the extensions here to be keyed by the full Script name and always include the base list.
  1280. auto extensions = move(script_extensions);
  1281. script_extensions = TRY(script_list.clone());
  1282. for (auto const& extension : extensions) {
  1283. auto it = find_if(script_aliases.begin(), script_aliases.end(), [&](auto const& alias) { return extension.key == alias.alias; });
  1284. auto const& key = (it == script_aliases.end()) ? extension.key : it->name;
  1285. auto& code_points = script_extensions.find(key)->value;
  1286. code_points.extend(extension.value);
  1287. sort_and_merge_code_point_ranges(code_points);
  1288. }
  1289. // Lastly, the Common and Inherited script extensions are special. They must not contain any
  1290. // code points which appear in other script extensions. The ScriptExtensions UCD file does not
  1291. // list these extensions, therefore this peculiarity must be handled programmatically.
  1292. // https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values
  1293. auto code_point_has_other_extension = [&](StringView key, u32 code_point) {
  1294. for (auto const& extension : extensions) {
  1295. if (extension.key == key)
  1296. continue;
  1297. if (any_of(extension.value, [&](auto const& r) { return (r.first <= code_point) && (code_point <= r.last); }))
  1298. return true;
  1299. }
  1300. return false;
  1301. };
  1302. auto get_code_points_without_other_extensions = [&](StringView key) {
  1303. auto code_points = flatten_code_point_ranges(script_list.find(key)->value);
  1304. code_points.remove_all_matching([&](u32 c) { return code_point_has_other_extension(key, c); });
  1305. return code_points;
  1306. };
  1307. auto common_code_points = get_code_points_without_other_extensions("Common"sv);
  1308. script_extensions.set("Common"sv, form_code_point_ranges(common_code_points));
  1309. auto inherited_code_points = get_code_points_without_other_extensions("Inherited"sv);
  1310. script_extensions.set("Inherited"sv, form_code_point_ranges(inherited_code_points));
  1311. return {};
  1312. }
  1313. struct CasingMetadata {
  1314. using ConstIterator = typename Vector<CodePointData>::ConstIterator;
  1315. CasingMetadata(Vector<CodePointData> const& code_point_data)
  1316. : iterator(code_point_data.begin())
  1317. , end(code_point_data.end())
  1318. {
  1319. }
  1320. ConstIterator iterator;
  1321. ConstIterator const end;
  1322. Vector<size_t> current_block;
  1323. HashMap<decltype(current_block), size_t> unique_blocks;
  1324. };
  1325. struct PropertyMetadata {
  1326. static ErrorOr<PropertyMetadata> create(PropList& property_list)
  1327. {
  1328. PropertyMetadata data;
  1329. TRY(data.property_values.try_ensure_capacity(property_list.size()));
  1330. TRY(data.property_set.try_ensure_capacity(property_list.size()));
  1331. auto property_names = property_list.keys();
  1332. quick_sort(property_names);
  1333. for (auto& property_name : property_names) {
  1334. auto& code_point_ranges = property_list.get(property_name).value();
  1335. data.property_values.unchecked_append(move(code_point_ranges));
  1336. }
  1337. return data;
  1338. }
  1339. Vector<typename PropList::ValueType> property_values;
  1340. PropertyTable property_set;
  1341. Vector<size_t> current_block;
  1342. HashMap<decltype(current_block), size_t> unique_blocks;
  1343. };
  1344. // The goal here is to produce a set of tables that represent a category of code point properties for every code point.
  1345. // The most naive method would be to generate a single table per category, each with one entry per code point. Each of
  1346. // those tables would have a size of 0x10ffff though, which is a non-starter. Instead, we create a set of 2-stage lookup
  1347. // tables per category.
  1348. //
  1349. // To do so, it's important to note that Unicode tends to organize code points with similar properties together. This
  1350. // leads to long series of code points with identical properties. Therefore, if we divide the 0x10ffff code points into
  1351. // fixed-size blocks, many of those blocks will also be identical.
  1352. //
  1353. // So we iterate over every code point, classifying each one for the category of interest. We represent a classification
  1354. // as a list of booleans. We store the classification in the CodePointTables::unique_properties list for this category.
  1355. // As the name implies, this list is de-duplicated; we store the index into this list in a separate list, which we call
  1356. // a "block".
  1357. //
  1358. // As we iterate, we "pause" every BLOCK_SIZE code points to examine the block. If the block is unique so far, we extend
  1359. // CodePointTables::stage2 with the entries of that block (so CodePointTables::stage2 is also a list of indices into
  1360. // CodePointTables::unique_properties). We then append the index of the start of that block in CodePointTables::stage2
  1361. // to CodePointTables::stage1.
  1362. //
  1363. // The value of BLOCK_SIZE is determined by CodePointTables::MSB_COUNT and CodePointTables::LSB_COUNT. We need 24 bits
  1364. // to describe all code points; the blocks we create are based on splitting these bits into 2 segments. We currently use
  1365. // a 16:8 bit split. So when perform a runtime lookup of a code point in the 2-stage tables, we:
  1366. //
  1367. // 1. Use most-significant 16 bits of the code point as the index into CodePointTables::stage1. That value is the
  1368. // index into CodePointTables::stage2 of the start of the block that contains properties for this code point.
  1369. //
  1370. // 2. Add the least-significant 8 bits of the code point to that value, to use as the index into
  1371. // CodePointTables::stage2. As described above, that value is the index into CodePointTables::unique_properties,
  1372. // which contains the classification for this code point.
  1373. //
  1374. // Using the code point GeneralCategory as an example, we end up with a CodePointTables::stage1 with a size of ~4000,
  1375. // a CodePointTables::stage2 with a size of ~40,000, and a CodePointTables::unique_properties with a size of ~30. So
  1376. // this process reduces over 1 million entries (0x10ffff) to ~44,030.
  1377. //
  1378. // For much more in-depth reading, see: https://icu.unicode.org/design/struct/utrie
  1379. static constexpr auto MAX_CODE_POINT = 0x10ffffu;
  1380. template<typename T>
  1381. static ErrorOr<void> update_tables(u32 code_point, CodePointTables<T>& tables, auto& metadata, auto const& values)
  1382. {
  1383. static constexpr auto BLOCK_SIZE = CODE_POINT_TABLES_LSB_MASK + 1;
  1384. size_t unique_properties_index = 0;
  1385. if (auto block_index = tables.unique_properties.find_first_index(values); block_index.has_value()) {
  1386. unique_properties_index = *block_index;
  1387. } else {
  1388. unique_properties_index = tables.unique_properties.size();
  1389. TRY(tables.unique_properties.try_append(values));
  1390. }
  1391. TRY(metadata.current_block.try_append(unique_properties_index));
  1392. if (metadata.current_block.size() == BLOCK_SIZE || code_point == MAX_CODE_POINT) {
  1393. size_t stage2_index = 0;
  1394. if (auto block_index = metadata.unique_blocks.get(metadata.current_block); block_index.has_value()) {
  1395. stage2_index = *block_index;
  1396. } else {
  1397. stage2_index = tables.stage2.size();
  1398. TRY(tables.stage2.try_extend(metadata.current_block));
  1399. TRY(metadata.unique_blocks.try_set(metadata.current_block, stage2_index));
  1400. }
  1401. TRY(tables.stage1.try_append(stage2_index));
  1402. metadata.current_block.clear_with_capacity();
  1403. }
  1404. return {};
  1405. }
  1406. static ErrorOr<void> create_code_point_tables(UnicodeData& unicode_data)
  1407. {
  1408. auto update_casing_tables = [&]<typename T>(u32 code_point, CodePointTables<T>& tables, CasingMetadata& metadata) -> ErrorOr<void> {
  1409. CasingTable casing {};
  1410. while (metadata.iterator != metadata.end) {
  1411. if (code_point < metadata.iterator->code_point)
  1412. break;
  1413. if (code_point == metadata.iterator->code_point) {
  1414. casing = move(metadata.iterator->casing);
  1415. break;
  1416. }
  1417. ++metadata.iterator;
  1418. }
  1419. TRY(update_tables(code_point, tables, metadata, casing));
  1420. return {};
  1421. };
  1422. auto update_property_tables = [&]<typename T>(u32 code_point, CodePointTables<T>& tables, PropertyMetadata& metadata) -> ErrorOr<void> {
  1423. static Unicode::CodePointRangeComparator comparator {};
  1424. for (auto& property_values : metadata.property_values) {
  1425. size_t ranges_to_remove = 0;
  1426. auto has_property = false;
  1427. for (auto const& range : property_values) {
  1428. if (auto comparison = comparator(code_point, range); comparison <= 0) {
  1429. has_property = comparison == 0;
  1430. break;
  1431. }
  1432. ++ranges_to_remove;
  1433. }
  1434. metadata.property_set.unchecked_append(has_property);
  1435. property_values.remove(0, ranges_to_remove);
  1436. }
  1437. TRY(update_tables(code_point, tables, metadata, metadata.property_set));
  1438. metadata.property_set.clear_with_capacity();
  1439. return {};
  1440. };
  1441. CasingMetadata casing_metadata { unicode_data.code_point_data };
  1442. auto general_category_metadata = TRY(PropertyMetadata::create(unicode_data.general_categories));
  1443. auto property_metadata = TRY(PropertyMetadata::create(unicode_data.prop_list));
  1444. auto script_metadata = TRY(PropertyMetadata::create(unicode_data.script_list));
  1445. auto script_extension_metadata = TRY(PropertyMetadata::create(unicode_data.script_extensions));
  1446. auto grapheme_break_metadata = TRY(PropertyMetadata::create(unicode_data.grapheme_break_props));
  1447. auto word_break_metadata = TRY(PropertyMetadata::create(unicode_data.word_break_props));
  1448. auto sentence_break_metadata = TRY(PropertyMetadata::create(unicode_data.sentence_break_props));
  1449. for (u32 code_point = 0; code_point <= MAX_CODE_POINT; ++code_point) {
  1450. TRY(update_casing_tables(code_point, unicode_data.casing_tables, casing_metadata));
  1451. TRY(update_property_tables(code_point, unicode_data.general_category_tables, general_category_metadata));
  1452. TRY(update_property_tables(code_point, unicode_data.property_tables, property_metadata));
  1453. TRY(update_property_tables(code_point, unicode_data.script_tables, script_metadata));
  1454. TRY(update_property_tables(code_point, unicode_data.script_extension_tables, script_extension_metadata));
  1455. TRY(update_property_tables(code_point, unicode_data.grapheme_break_tables, grapheme_break_metadata));
  1456. TRY(update_property_tables(code_point, unicode_data.word_break_tables, word_break_metadata));
  1457. TRY(update_property_tables(code_point, unicode_data.sentence_break_tables, sentence_break_metadata));
  1458. }
  1459. return {};
  1460. }
  1461. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1462. {
  1463. StringView generated_header_path;
  1464. StringView generated_implementation_path;
  1465. StringView unicode_data_path;
  1466. StringView special_casing_path;
  1467. StringView case_folding_path;
  1468. StringView derived_general_category_path;
  1469. StringView prop_list_path;
  1470. StringView derived_core_prop_path;
  1471. StringView derived_binary_prop_path;
  1472. StringView prop_alias_path;
  1473. StringView prop_value_alias_path;
  1474. StringView name_alias_path;
  1475. StringView scripts_path;
  1476. StringView script_extensions_path;
  1477. StringView blocks_path;
  1478. StringView emoji_data_path;
  1479. StringView normalization_path;
  1480. StringView grapheme_break_path;
  1481. StringView word_break_path;
  1482. StringView sentence_break_path;
  1483. Core::ArgsParser args_parser;
  1484. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  1485. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  1486. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  1487. args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
  1488. args_parser.add_option(case_folding_path, "Path to CaseFolding.txt file", "case-folding-path", 'o', "case-folding-path");
  1489. args_parser.add_option(derived_general_category_path, "Path to DerivedGeneralCategory.txt file", "derived-general-category-path", 'g', "derived-general-category-path");
  1490. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  1491. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  1492. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  1493. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  1494. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  1495. args_parser.add_option(name_alias_path, "Path to NameAliases.txt file", "name-alias-path", 'm', "name-alias-path");
  1496. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  1497. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  1498. args_parser.add_option(blocks_path, "Path to Blocks.txt file", "blocks-path", 'k', "blocks-path");
  1499. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  1500. args_parser.add_option(normalization_path, "Path to DerivedNormalizationProps.txt file", "normalization-path", 'n', "normalization-path");
  1501. args_parser.add_option(grapheme_break_path, "Path to GraphemeBreakProperty.txt file", "grapheme-break-path", 'f', "grapheme-break-path");
  1502. args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path");
  1503. args_parser.add_option(sentence_break_path, "Path to SentenceBreakProperty.txt file", "sentence-break-path", 'i', "sentence-break-path");
  1504. args_parser.parse(arguments);
  1505. auto generated_header_file = TRY(open_file(generated_header_path, Core::File::OpenMode::Write));
  1506. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::File::OpenMode::Write));
  1507. auto unicode_data_file = TRY(open_file(unicode_data_path, Core::File::OpenMode::Read));
  1508. auto derived_general_category_file = TRY(open_file(derived_general_category_path, Core::File::OpenMode::Read));
  1509. auto special_casing_file = TRY(open_file(special_casing_path, Core::File::OpenMode::Read));
  1510. auto case_folding_file = TRY(open_file(case_folding_path, Core::File::OpenMode::Read));
  1511. auto prop_list_file = TRY(open_file(prop_list_path, Core::File::OpenMode::Read));
  1512. auto derived_core_prop_file = TRY(open_file(derived_core_prop_path, Core::File::OpenMode::Read));
  1513. auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path, Core::File::OpenMode::Read));
  1514. auto prop_alias_file = TRY(open_file(prop_alias_path, Core::File::OpenMode::Read));
  1515. auto prop_value_alias_file = TRY(open_file(prop_value_alias_path, Core::File::OpenMode::Read));
  1516. auto name_alias_file = TRY(open_file(name_alias_path, Core::File::OpenMode::Read));
  1517. auto scripts_file = TRY(open_file(scripts_path, Core::File::OpenMode::Read));
  1518. auto script_extensions_file = TRY(open_file(script_extensions_path, Core::File::OpenMode::Read));
  1519. auto blocks_file = TRY(open_file(blocks_path, Core::File::OpenMode::Read));
  1520. auto emoji_data_file = TRY(open_file(emoji_data_path, Core::File::OpenMode::Read));
  1521. auto normalization_file = TRY(open_file(normalization_path, Core::File::OpenMode::Read));
  1522. auto grapheme_break_file = TRY(open_file(grapheme_break_path, Core::File::OpenMode::Read));
  1523. auto word_break_file = TRY(open_file(word_break_path, Core::File::OpenMode::Read));
  1524. auto sentence_break_file = TRY(open_file(sentence_break_path, Core::File::OpenMode::Read));
  1525. UnicodeData unicode_data {};
  1526. TRY(parse_special_casing(*special_casing_file, unicode_data));
  1527. TRY(parse_case_folding(*case_folding_file, unicode_data));
  1528. TRY(parse_prop_list(*derived_general_category_file, unicode_data.general_categories));
  1529. TRY(parse_prop_list(*prop_list_file, unicode_data.prop_list));
  1530. TRY(parse_prop_list(*derived_core_prop_file, unicode_data.prop_list));
  1531. TRY(parse_prop_list(*derived_binary_prop_file, unicode_data.prop_list));
  1532. TRY(parse_prop_list(*emoji_data_file, unicode_data.prop_list));
  1533. TRY(parse_normalization_props(*normalization_file, unicode_data));
  1534. TRY(parse_alias_list(*prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases));
  1535. TRY(parse_prop_list(*scripts_file, unicode_data.script_list));
  1536. TRY(parse_prop_list(*script_extensions_file, unicode_data.script_extensions, true));
  1537. TRY(parse_block_display_names(*blocks_file, unicode_data));
  1538. TRY(parse_name_aliases(*name_alias_file, unicode_data));
  1539. TRY(parse_prop_list(*grapheme_break_file, unicode_data.grapheme_break_props));
  1540. TRY(parse_prop_list(*word_break_file, unicode_data.word_break_props));
  1541. TRY(parse_prop_list(*sentence_break_file, unicode_data.sentence_break_props));
  1542. populate_general_category_unions(unicode_data.general_categories);
  1543. TRY(parse_unicode_data(*unicode_data_file, unicode_data));
  1544. TRY(parse_value_alias_list(*prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases));
  1545. TRY(parse_value_alias_list(*prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false));
  1546. TRY(normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases));
  1547. TRY(create_code_point_tables(unicode_data));
  1548. TRY(generate_unicode_data_header(*generated_header_file, unicode_data));
  1549. TRY(generate_unicode_data_implementation(*generated_implementation_file, unicode_data));
  1550. return 0;
  1551. }