GenerateUnicodeData.cpp 75 KB

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