GenerateUnicodeData.cpp 77 KB

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