GenerateUnicodeData.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AllOf.h>
  7. #include <AK/Array.h>
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/Optional.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/SourceGenerator.h>
  13. #include <AK/String.h>
  14. #include <AK/StringUtils.h>
  15. #include <AK/Types.h>
  16. #include <AK/Vector.h>
  17. #include <LibCore/ArgsParser.h>
  18. #include <LibCore/File.h>
  19. // Some code points are excluded from UnicodeData.txt, and instead are part of a "range" of code
  20. // points, as indicated by the "name" field. For example:
  21. // 3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;
  22. // 4DBF;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;
  23. struct CodePointRange {
  24. u32 first;
  25. u32 last;
  26. };
  27. // SpecialCasing source: https://www.unicode.org/Public/13.0.0/ucd/SpecialCasing.txt
  28. // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#SpecialCasing.txt
  29. struct SpecialCasing {
  30. u32 index { 0 };
  31. u32 code_point { 0 };
  32. Vector<u32> lowercase_mapping;
  33. Vector<u32> uppercase_mapping;
  34. Vector<u32> titlecase_mapping;
  35. String locale;
  36. String condition;
  37. };
  38. // PropList source: https://www.unicode.org/Public/13.0.0/ucd/PropList.txt
  39. // Property descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#PropList.txt
  40. // https://www.unicode.org/reports/tr44/tr44-13.html#WordBreakProperty.txt
  41. using PropList = HashMap<String, Vector<CodePointRange>>;
  42. // PropertyAliases source: https://www.unicode.org/Public/13.0.0/ucd/PropertyAliases.txt
  43. struct Alias {
  44. String property;
  45. String alias;
  46. };
  47. // UnicodeData source: https://www.unicode.org/Public/13.0.0/ucd/UnicodeData.txt
  48. // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#UnicodeData.txt
  49. // https://www.unicode.org/reports/tr44/#General_Category_Values
  50. struct CodePointData {
  51. u32 code_point { 0 };
  52. String name;
  53. String general_category;
  54. u8 canonical_combining_class { 0 };
  55. String bidi_class;
  56. String decomposition_type;
  57. Optional<i8> numeric_value_decimal;
  58. Optional<i8> numeric_value_digit;
  59. Optional<i8> numeric_value_numeric;
  60. bool bidi_mirrored { false };
  61. String unicode_1_name;
  62. String iso_comment;
  63. Optional<u32> simple_uppercase_mapping;
  64. Optional<u32> simple_lowercase_mapping;
  65. Optional<u32> simple_titlecase_mapping;
  66. Vector<u32> special_casing_indices;
  67. Vector<StringView> prop_list;
  68. StringView script;
  69. Vector<StringView> script_extensions;
  70. StringView word_break_property;
  71. };
  72. struct UnicodeData {
  73. Vector<SpecialCasing> special_casing;
  74. u32 largest_casing_transform_size { 0 };
  75. u32 largest_special_casing_size { 0 };
  76. Vector<String> locales;
  77. Vector<String> conditions;
  78. Vector<CodePointData> code_point_data;
  79. Vector<CodePointRange> code_point_ranges;
  80. // The Unicode standard defines General Category values which are not in any UCD file. These
  81. // values are simply unions of other values.
  82. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  83. Vector<String> general_categories;
  84. Vector<Alias> general_category_unions {
  85. { "Ll | Lu | Lt"sv, "LC"sv },
  86. { "Lu | Ll | Lt | Lm | Lo"sv, "L"sv },
  87. { "Mn | Mc | Me"sv, "M"sv },
  88. { "Nd | Nl | No"sv, "N"sv },
  89. { "Pc | Pd | Ps | Pe | Pi | Pf | Po"sv, "P"sv },
  90. { "Sm | Sc | Sk | So"sv, "S"sv },
  91. { "Zs | Zl | Zp"sv, "Z"sv },
  92. { "Cc | Cf | Cs | Co"sv, "C"sv }, // FIXME: This union should also contain "Cn" (Unassigned), which we don't parse yet.
  93. };
  94. Vector<Alias> general_category_aliases;
  95. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  96. // any UCD file. Assigned is set as the default enum value 0 so "property & Assigned == Assigned"
  97. // is always true. Any is not assigned code points here because this file only parses assigned
  98. // code points, whereas Any will include unassigned code points.
  99. // https://unicode.org/reports/tr18/#General_Category_Property
  100. PropList prop_list {
  101. { "Any"sv, {} },
  102. { "ASCII"sv, { { 0, 0x7f } } },
  103. };
  104. Vector<Alias> prop_aliases;
  105. PropList script_list {
  106. { "Unknown"sv, {} },
  107. };
  108. Vector<Alias> script_aliases;
  109. PropList script_extensions;
  110. u32 largest_script_extensions_size { 0 };
  111. PropList word_break_prop_list;
  112. };
  113. static constexpr auto s_desired_fields = Array {
  114. "general_category"sv,
  115. "simple_uppercase_mapping"sv,
  116. "simple_lowercase_mapping"sv,
  117. };
  118. static void write_to_file_if_different(Core::File& file, StringView contents)
  119. {
  120. auto const current_contents = file.read_all();
  121. if (StringView { current_contents.bytes() } == contents)
  122. return;
  123. VERIFY(file.seek(0));
  124. VERIFY(file.truncate(0));
  125. VERIFY(file.write(contents));
  126. }
  127. static void parse_special_casing(Core::File& file, UnicodeData& unicode_data)
  128. {
  129. auto parse_code_point_list = [&](auto const& line) {
  130. Vector<u32> code_points;
  131. auto segments = line.split(' ');
  132. for (auto const& code_point : segments)
  133. code_points.append(AK::StringUtils::convert_to_uint_from_hex<u32>(code_point).value());
  134. return code_points;
  135. };
  136. while (file.can_read_line()) {
  137. auto line = file.read_line();
  138. if (line.is_empty() || line.starts_with('#'))
  139. continue;
  140. if (auto index = line.find('#'); index.has_value())
  141. line = line.substring(0, *index);
  142. auto segments = line.split(';', true);
  143. VERIFY(segments.size() == 5 || segments.size() == 6);
  144. SpecialCasing casing {};
  145. casing.index = static_cast<u32>(unicode_data.special_casing.size());
  146. casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  147. casing.lowercase_mapping = parse_code_point_list(segments[1]);
  148. casing.titlecase_mapping = parse_code_point_list(segments[2]);
  149. casing.uppercase_mapping = parse_code_point_list(segments[3]);
  150. if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
  151. auto conditions = condition.split(' ', true);
  152. VERIFY(conditions.size() == 1 || conditions.size() == 2);
  153. if (conditions.size() == 2) {
  154. casing.locale = move(conditions[0]);
  155. casing.condition = move(conditions[1]);
  156. } else if (all_of(conditions[0], is_ascii_lower_alpha)) {
  157. casing.locale = move(conditions[0]);
  158. } else {
  159. casing.condition = move(conditions[0]);
  160. }
  161. casing.locale = casing.locale.to_uppercase();
  162. casing.condition.replace("_", "", true);
  163. if (!casing.locale.is_empty() && !unicode_data.locales.contains_slow(casing.locale))
  164. unicode_data.locales.append(casing.locale);
  165. if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
  166. unicode_data.conditions.append(casing.condition);
  167. }
  168. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.lowercase_mapping.size());
  169. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.titlecase_mapping.size());
  170. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.uppercase_mapping.size());
  171. unicode_data.special_casing.append(move(casing));
  172. }
  173. }
  174. static void parse_prop_list(Core::File& file, PropList& prop_list, bool multi_value_property = false)
  175. {
  176. while (file.can_read_line()) {
  177. auto line = file.read_line();
  178. if (line.is_empty() || line.starts_with('#'))
  179. continue;
  180. if (auto index = line.find('#'); index.has_value())
  181. line = line.substring(0, *index);
  182. auto segments = line.split_view(';', true);
  183. VERIFY(segments.size() == 2);
  184. auto code_point_range = segments[0].trim_whitespace();
  185. Vector<StringView> properties;
  186. if (multi_value_property)
  187. properties = segments[1].trim_whitespace().split_view(' ');
  188. else
  189. properties = { segments[1].trim_whitespace() };
  190. for (auto const& property : properties) {
  191. auto& code_points = prop_list.ensure(property.trim_whitespace());
  192. if (code_point_range.contains(".."sv)) {
  193. segments = code_point_range.split_view(".."sv);
  194. VERIFY(segments.size() == 2);
  195. auto begin = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  196. auto end = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[1]).value();
  197. code_points.append({ begin, end });
  198. } else {
  199. auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(code_point_range).value();
  200. code_points.append({ code_point, code_point });
  201. }
  202. }
  203. }
  204. }
  205. static void parse_alias_list(Core::File& file, PropList const& prop_list, Vector<Alias>& prop_aliases)
  206. {
  207. String current_property;
  208. auto append_alias = [&](auto alias, auto property) {
  209. // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip.
  210. if (alias == property)
  211. return;
  212. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  213. if (!prop_list.contains(property))
  214. return;
  215. prop_aliases.append({ property, alias });
  216. };
  217. while (file.can_read_line()) {
  218. auto line = file.read_line();
  219. if (line.is_empty() || line.starts_with('#')) {
  220. if (line.ends_with("Properties"sv))
  221. current_property = line.substring(2);
  222. continue;
  223. }
  224. // Note: For now, we only care about Binary Property aliases for Unicode property escapes.
  225. if (current_property != "Binary Properties"sv)
  226. continue;
  227. auto segments = line.split_view(';', true);
  228. VERIFY((segments.size() == 2) || (segments.size() == 3));
  229. auto alias = segments[0].trim_whitespace();
  230. auto property = segments[1].trim_whitespace();
  231. append_alias(alias, property);
  232. if (segments.size() == 3) {
  233. alias = segments[2].trim_whitespace();
  234. append_alias(alias, property);
  235. }
  236. }
  237. }
  238. static void parse_value_alias_list(Core::File& file, StringView desired_category, Vector<String> const& value_list, Vector<Alias> const& prop_unions, Vector<Alias>& prop_aliases, bool primary_value_is_first = true)
  239. {
  240. VERIFY(file.seek(0));
  241. auto append_alias = [&](auto alias, auto value) {
  242. // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip.
  243. if (alias == value)
  244. return;
  245. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  246. if (!value_list.contains_slow(value) && !any_of(prop_unions, [&](auto const& u) { return value == u.alias; }))
  247. return;
  248. prop_aliases.append({ value, alias });
  249. };
  250. while (file.can_read_line()) {
  251. auto line = file.read_line();
  252. if (line.is_empty() || line.starts_with('#'))
  253. continue;
  254. if (auto index = line.find('#'); index.has_value())
  255. line = line.substring(0, *index);
  256. auto segments = line.split_view(';', true);
  257. auto category = segments[0].trim_whitespace();
  258. if (category != desired_category)
  259. continue;
  260. VERIFY((segments.size() == 3) || (segments.size() == 4));
  261. auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace();
  262. auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace();
  263. append_alias(alias, value);
  264. if (segments.size() == 4) {
  265. alias = segments[3].trim_whitespace();
  266. append_alias(alias, value);
  267. }
  268. }
  269. }
  270. static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data)
  271. {
  272. Optional<u32> code_point_range_start;
  273. auto assign_code_point_property = [&](u32 code_point, auto const& list, auto& property, StringView default_) {
  274. using PropertyType = RemoveCVReference<decltype(property)>;
  275. constexpr bool is_single_item = IsSame<PropertyType, StringView>;
  276. auto assign_property = [&](auto const& item) {
  277. if constexpr (is_single_item)
  278. property = item;
  279. else
  280. property.append(item);
  281. };
  282. for (auto const& item : list) {
  283. for (auto const& range : item.value) {
  284. if ((range.first <= code_point) && (code_point <= range.last)) {
  285. assign_property(item.key);
  286. break;
  287. }
  288. }
  289. if constexpr (is_single_item) {
  290. if (!property.is_empty())
  291. break;
  292. }
  293. }
  294. if (property.is_empty() && !default_.is_empty())
  295. assign_property(default_);
  296. };
  297. while (file.can_read_line()) {
  298. auto line = file.read_line();
  299. if (line.is_empty())
  300. continue;
  301. auto segments = line.split(';', true);
  302. VERIFY(segments.size() == 15);
  303. CodePointData data {};
  304. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  305. data.name = move(segments[1]);
  306. data.general_category = move(segments[2]);
  307. data.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
  308. data.bidi_class = move(segments[4]);
  309. data.decomposition_type = move(segments[5]);
  310. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  311. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  312. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  313. data.bidi_mirrored = segments[9] == "Y"sv;
  314. data.unicode_1_name = move(segments[10]);
  315. data.iso_comment = move(segments[11]);
  316. data.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
  317. data.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
  318. data.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
  319. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>")) {
  320. VERIFY(!code_point_range_start.has_value());
  321. code_point_range_start = data.code_point;
  322. data.name = data.name.substring(1, data.name.length() - 9);
  323. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>")) {
  324. VERIFY(code_point_range_start.has_value());
  325. unicode_data.code_point_ranges.append({ *code_point_range_start, data.code_point });
  326. data.name = data.name.substring(1, data.name.length() - 8);
  327. code_point_range_start.clear();
  328. }
  329. for (auto const& casing : unicode_data.special_casing) {
  330. if (casing.code_point == data.code_point)
  331. data.special_casing_indices.append(casing.index);
  332. }
  333. assign_code_point_property(data.code_point, unicode_data.prop_list, data.prop_list, "Assigned"sv);
  334. assign_code_point_property(data.code_point, unicode_data.script_list, data.script, "Unknown"sv);
  335. assign_code_point_property(data.code_point, unicode_data.script_extensions, data.script_extensions, {});
  336. assign_code_point_property(data.code_point, unicode_data.word_break_prop_list, data.word_break_property, "Other"sv);
  337. unicode_data.largest_special_casing_size = max(unicode_data.largest_special_casing_size, data.special_casing_indices.size());
  338. unicode_data.largest_script_extensions_size = max(unicode_data.largest_script_extensions_size, data.script_extensions.size());
  339. if (!unicode_data.general_categories.contains_slow(data.general_category))
  340. unicode_data.general_categories.append(data.general_category);
  341. unicode_data.code_point_data.append(move(data));
  342. }
  343. }
  344. static void generate_unicode_data_header(Core::File& file, UnicodeData& unicode_data)
  345. {
  346. StringBuilder builder;
  347. SourceGenerator generator { builder };
  348. generator.set("casing_transform_size", String::number(unicode_data.largest_casing_transform_size));
  349. generator.set("special_casing_size", String::number(unicode_data.largest_special_casing_size));
  350. generator.set("script_extensions_size", String::number(unicode_data.largest_script_extensions_size));
  351. auto generate_enum = [&](StringView name, StringView default_, Vector<String> values, Vector<Alias> unions = {}, Vector<Alias> aliases = {}, bool as_bitmask = false) {
  352. VERIFY(!as_bitmask || (values.size() <= 64));
  353. quick_sort(values);
  354. quick_sort(unions, [](auto& union1, auto& union2) { return union1.alias < union2.alias; });
  355. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  356. generator.set("name", name);
  357. generator.set("underlying", String::formatted("{}UnderlyingType", name));
  358. if (as_bitmask) {
  359. generator.append(R"~~~(
  360. using @underlying@ = u64;
  361. enum class @name@ : @underlying@ {)~~~");
  362. } else {
  363. generator.append(R"~~~(
  364. enum class @name@ {)~~~");
  365. }
  366. if (!default_.is_empty()) {
  367. generator.set("default", default_);
  368. generator.append(R"~~~(
  369. @default@,)~~~");
  370. }
  371. u8 index = 0;
  372. for (auto const& value : values) {
  373. generator.set("value", value);
  374. if (as_bitmask) {
  375. generator.set("index", String::number(index++));
  376. generator.append(R"~~~(
  377. @value@ = static_cast<@underlying@>(1) << @index@,)~~~");
  378. } else {
  379. generator.append(R"~~~(
  380. @value@,)~~~");
  381. }
  382. }
  383. for (auto const& union_ : unions) {
  384. generator.set("union", union_.alias);
  385. generator.set("value", union_.property);
  386. generator.append(R"~~~(
  387. @union@ = @value@,)~~~");
  388. }
  389. for (auto const& alias : aliases) {
  390. generator.set("alias", alias.alias);
  391. generator.set("value", alias.property);
  392. generator.append(R"~~~(
  393. @alias@ = @value@,)~~~");
  394. }
  395. generator.append(R"~~~(
  396. };
  397. )~~~");
  398. if (as_bitmask) {
  399. generator.append(R"~~~(
  400. constexpr @name@ operator&(@name@ value1, @name@ value2)
  401. {
  402. return static_cast<@name@>(static_cast<@underlying@>(value1) & static_cast<@underlying@>(value2));
  403. }
  404. constexpr @name@ operator|(@name@ value1, @name@ value2)
  405. {
  406. return static_cast<@name@>(static_cast<@underlying@>(value1) | static_cast<@underlying@>(value2));
  407. }
  408. )~~~");
  409. }
  410. };
  411. generator.append(R"~~~(
  412. #pragma once
  413. #include <AK/Optional.h>
  414. #include <AK/Types.h>
  415. #include <LibUnicode/Forward.h>
  416. namespace Unicode {
  417. )~~~");
  418. generate_enum("Locale"sv, "None"sv, move(unicode_data.locales));
  419. generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
  420. generate_enum("GeneralCategory"sv, "None"sv, unicode_data.general_categories, unicode_data.general_category_unions, unicode_data.general_category_aliases, true);
  421. generate_enum("Property"sv, "Assigned"sv, unicode_data.prop_list.keys(), {}, unicode_data.prop_aliases, true);
  422. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), {}, unicode_data.script_aliases);
  423. generate_enum("WordBreakProperty"sv, "Other"sv, unicode_data.word_break_prop_list.keys());
  424. generator.append(R"~~~(
  425. struct SpecialCasing {
  426. u32 code_point { 0 };
  427. u32 lowercase_mapping[@casing_transform_size@];
  428. u32 lowercase_mapping_size { 0 };
  429. u32 uppercase_mapping[@casing_transform_size@];
  430. u32 uppercase_mapping_size { 0 };
  431. u32 titlecase_mapping[@casing_transform_size@];
  432. u32 titlecase_mapping_size { 0 };
  433. Locale locale { Locale::None };
  434. Condition condition { Condition::None };
  435. };
  436. struct UnicodeData {
  437. u32 code_point;)~~~");
  438. auto append_field = [&](StringView type, StringView name) {
  439. if (!s_desired_fields.span().contains_slow(name))
  440. return;
  441. generator.set("type", type);
  442. generator.set("name", name);
  443. generator.append(R"~~~(
  444. @type@ @name@;)~~~");
  445. };
  446. // Note: For compile-time performance, only primitive types are used.
  447. append_field("char const*"sv, "name"sv);
  448. append_field("GeneralCategory"sv, "general_category"sv);
  449. append_field("u8"sv, "canonical_combining_class"sv);
  450. append_field("char const*"sv, "bidi_class"sv);
  451. append_field("char const*"sv, "decomposition_type"sv);
  452. append_field("i8"sv, "numeric_value_decimal"sv);
  453. append_field("i8"sv, "numeric_value_digit"sv);
  454. append_field("i8"sv, "numeric_value_numeric"sv);
  455. append_field("bool"sv, "bidi_mirrored"sv);
  456. append_field("char const*"sv, "unicode_1_name"sv);
  457. append_field("char const*"sv, "iso_comment"sv);
  458. append_field("u32"sv, "simple_uppercase_mapping"sv);
  459. append_field("u32"sv, "simple_lowercase_mapping"sv);
  460. append_field("u32"sv, "simple_titlecase_mapping"sv);
  461. generator.append(R"~~~(
  462. SpecialCasing const* special_casing[@special_casing_size@] {};
  463. u32 special_casing_size { 0 };
  464. Property properties { Property::Assigned };
  465. Script script { Script::Unknown };
  466. Script script_extensions[@script_extensions_size@];
  467. u32 script_extensions_size { 0 };
  468. WordBreakProperty word_break_property { WordBreakProperty::Other };
  469. };
  470. namespace Detail {
  471. Optional<UnicodeData> unicode_data_for_code_point(u32 code_point);
  472. Optional<Property> property_from_string(StringView const& property);
  473. Optional<GeneralCategory> general_category_from_string(StringView const& general_category);
  474. Optional<Script> script_from_string(StringView const& script);
  475. }
  476. }
  477. )~~~");
  478. write_to_file_if_different(file, generator.as_string_view());
  479. }
  480. static void generate_unicode_data_implementation(Core::File& file, UnicodeData const& unicode_data)
  481. {
  482. StringBuilder builder;
  483. SourceGenerator generator { builder };
  484. generator.set("special_casing_size", String::number(unicode_data.special_casing.size()));
  485. generator.set("code_point_data_size", String::number(unicode_data.code_point_data.size()));
  486. generator.append(R"~~~(
  487. #include <AK/Array.h>
  488. #include <AK/CharacterTypes.h>
  489. #include <AK/HashMap.h>
  490. #include <AK/StringView.h>
  491. #include <LibUnicode/UnicodeData.h>
  492. namespace Unicode {
  493. )~~~");
  494. auto append_list_and_size = [&](auto const& list, StringView format) {
  495. if (list.is_empty()) {
  496. generator.append(", {}, 0");
  497. return;
  498. }
  499. bool first = true;
  500. generator.append(", {");
  501. for (auto const& item : list) {
  502. generator.append(first ? " " : ", ");
  503. generator.append(String::formatted(format, item));
  504. first = false;
  505. }
  506. generator.append(String::formatted(" }}, {}", list.size()));
  507. };
  508. generator.append(R"~~~(
  509. static constexpr Array<SpecialCasing, @special_casing_size@> s_special_casing { {)~~~");
  510. for (auto const& casing : unicode_data.special_casing) {
  511. generator.set("code_point", String::formatted("{:#x}", casing.code_point));
  512. generator.append(R"~~~(
  513. { @code_point@)~~~");
  514. constexpr auto format = "0x{:x}"sv;
  515. append_list_and_size(casing.lowercase_mapping, format);
  516. append_list_and_size(casing.uppercase_mapping, format);
  517. append_list_and_size(casing.titlecase_mapping, format);
  518. generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
  519. generator.append(", Locale::@locale@");
  520. generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
  521. generator.append(", Condition::@condition@");
  522. generator.append(" },");
  523. }
  524. generator.append(R"~~~(
  525. } };
  526. static constexpr Array<UnicodeData, @code_point_data_size@> s_unicode_data { {)~~~");
  527. auto append_field = [&](StringView name, String value) {
  528. if (!s_desired_fields.span().contains_slow(name))
  529. return;
  530. generator.set("value", move(value));
  531. generator.append(", @value@");
  532. };
  533. for (auto const& data : unicode_data.code_point_data) {
  534. generator.set("code_point", String::formatted("{:#x}", data.code_point));
  535. generator.append(R"~~~(
  536. { @code_point@)~~~");
  537. append_field("name", String::formatted("\"{}\"", data.name));
  538. append_field("general_category", String::formatted("GeneralCategory::{}", data.general_category));
  539. append_field("canonical_combining_class", String::number(data.canonical_combining_class));
  540. append_field("bidi_class", String::formatted("\"{}\"", data.bidi_class));
  541. append_field("decomposition_type", String::formatted("\"{}\"", data.decomposition_type));
  542. append_field("numeric_value_decimal", String::number(data.numeric_value_decimal.value_or(-1)));
  543. append_field("numeric_value_digit", String::number(data.numeric_value_digit.value_or(-1)));
  544. append_field("numeric_value_numeric", String::number(data.numeric_value_numeric.value_or(-1)));
  545. append_field("bidi_mirrored", String::formatted("{}", data.bidi_mirrored));
  546. append_field("unicode_1_name", String::formatted("\"{}\"", data.unicode_1_name));
  547. append_field("iso_comment", String::formatted("\"{}\"", data.iso_comment));
  548. append_field("simple_uppercase_mapping", String::formatted("{:#x}", data.simple_uppercase_mapping.value_or(data.code_point)));
  549. append_field("simple_lowercase_mapping", String::formatted("{:#x}", data.simple_lowercase_mapping.value_or(data.code_point)));
  550. append_field("simple_titlecase_mapping", String::formatted("{:#x}", data.simple_titlecase_mapping.value_or(data.code_point)));
  551. append_list_and_size(data.special_casing_indices, "&s_special_casing[{}]"sv);
  552. bool first = true;
  553. for (auto const& property : data.prop_list) {
  554. generator.append(first ? ", " : " | ");
  555. generator.append(String::formatted("Property::{}", property));
  556. first = false;
  557. }
  558. generator.append(String::formatted(", Script::{}", data.script));
  559. append_list_and_size(data.script_extensions, "Script::{}"sv);
  560. generator.append(String::formatted(", WordBreakProperty::{}", data.word_break_property));
  561. generator.append(" },");
  562. }
  563. generator.append(R"~~~(
  564. } };
  565. static HashMap<u32, UnicodeData const*> const& ensure_code_point_map()
  566. {
  567. static HashMap<u32, UnicodeData const*> code_point_to_data_map;
  568. code_point_to_data_map.ensure_capacity(s_unicode_data.size());
  569. for (auto const& unicode_data : s_unicode_data)
  570. code_point_to_data_map.set(unicode_data.code_point, &unicode_data);
  571. return code_point_to_data_map;
  572. }
  573. static Optional<u32> index_of_code_point_in_range(u32 code_point)
  574. {)~~~");
  575. for (auto const& range : unicode_data.code_point_ranges) {
  576. generator.set("first", String::formatted("{:#x}", range.first));
  577. generator.set("last", String::formatted("{:#x}", range.last));
  578. generator.append(R"~~~(
  579. if ((code_point > @first@) && (code_point < @last@))
  580. return @first@;)~~~");
  581. }
  582. generator.append(R"~~~(
  583. return {};
  584. }
  585. namespace Detail {
  586. Optional<UnicodeData> unicode_data_for_code_point(u32 code_point)
  587. {
  588. static auto const& code_point_to_data_map = ensure_code_point_map();
  589. VERIFY(is_unicode(code_point));
  590. if (auto data = code_point_to_data_map.get(code_point); data.has_value())
  591. return *(data.value());
  592. if (auto index = index_of_code_point_in_range(code_point); index.has_value()) {
  593. auto data_for_range = *(code_point_to_data_map.get(*index).value());
  594. data_for_range.simple_uppercase_mapping = code_point;
  595. data_for_range.simple_lowercase_mapping = code_point;
  596. return data_for_range;
  597. }
  598. return {};
  599. }
  600. Optional<Property> property_from_string(StringView const& property)
  601. {
  602. if (property == "Assigned"sv)
  603. return Property::Assigned;)~~~");
  604. for (auto const& property : unicode_data.prop_list) {
  605. generator.set("property", property.key);
  606. generator.append(R"~~~(
  607. if (property == "@property@"sv)
  608. return Property::@property@;)~~~");
  609. }
  610. for (auto const& alias : unicode_data.prop_aliases) {
  611. generator.set("property", alias.alias);
  612. generator.append(R"~~~(
  613. if (property == "@property@"sv)
  614. return Property::@property@;)~~~");
  615. }
  616. generator.append(R"~~~(
  617. return {};
  618. }
  619. Optional<GeneralCategory> general_category_from_string(StringView const& general_category)
  620. {)~~~");
  621. for (auto const& general_category : unicode_data.general_categories) {
  622. generator.set("general_category", general_category);
  623. generator.append(R"~~~(
  624. if (general_category == "@general_category@"sv)
  625. return GeneralCategory::@general_category@;)~~~");
  626. }
  627. for (auto const& union_ : unicode_data.general_category_unions) {
  628. generator.set("general_category", union_.alias);
  629. generator.append(R"~~~(
  630. if (general_category == "@general_category@"sv)
  631. return GeneralCategory::@general_category@;)~~~");
  632. }
  633. for (auto const& alias : unicode_data.general_category_aliases) {
  634. generator.set("general_category", alias.alias);
  635. generator.append(R"~~~(
  636. if (general_category == "@general_category@"sv)
  637. return GeneralCategory::@general_category@;)~~~");
  638. }
  639. generator.append(R"~~~(
  640. return {};
  641. }
  642. Optional<Script> script_from_string(StringView const& script)
  643. {)~~~");
  644. for (auto const& script : unicode_data.script_list) {
  645. generator.set("script", script.key);
  646. generator.append(R"~~~(
  647. if (script == "@script@"sv)
  648. return Script::@script@;)~~~");
  649. }
  650. for (auto const& alias : unicode_data.script_aliases) {
  651. generator.set("script", alias.alias);
  652. generator.append(R"~~~(
  653. if (script == "@script@"sv)
  654. return Script::@script@;)~~~");
  655. }
  656. generator.append(R"~~~(
  657. return {};
  658. }
  659. }
  660. }
  661. )~~~");
  662. write_to_file_if_different(file, generator.as_string_view());
  663. }
  664. int main(int argc, char** argv)
  665. {
  666. char const* generated_header_path = nullptr;
  667. char const* generated_implementation_path = nullptr;
  668. char const* unicode_data_path = nullptr;
  669. char const* special_casing_path = nullptr;
  670. char const* prop_list_path = nullptr;
  671. char const* derived_core_prop_path = nullptr;
  672. char const* derived_binary_prop_path = nullptr;
  673. char const* prop_alias_path = nullptr;
  674. char const* prop_value_alias_path = nullptr;
  675. char const* scripts_path = nullptr;
  676. char const* script_extensions_path = nullptr;
  677. char const* word_break_path = nullptr;
  678. char const* emoji_data_path = nullptr;
  679. Core::ArgsParser args_parser;
  680. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  681. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  682. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  683. args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
  684. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  685. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  686. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  687. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  688. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  689. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  690. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  691. args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path");
  692. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  693. args_parser.parse(argc, argv);
  694. auto open_file = [&](StringView path, StringView flags, Core::OpenMode mode = Core::OpenMode::ReadOnly) {
  695. if (path.is_empty()) {
  696. warnln("{} is required", flags);
  697. args_parser.print_usage(stderr, argv[0]);
  698. exit(1);
  699. }
  700. auto file_or_error = Core::File::open(path, mode);
  701. if (file_or_error.is_error()) {
  702. warnln("Failed to open {}: {}", path, file_or_error.release_error());
  703. exit(1);
  704. }
  705. return file_or_error.release_value();
  706. };
  707. auto generated_header_file = open_file(generated_header_path, "-h/--generated-header-path", Core::OpenMode::ReadWrite);
  708. auto generated_implementation_file = open_file(generated_implementation_path, "-c/--generated-implementation-path", Core::OpenMode::ReadWrite);
  709. auto unicode_data_file = open_file(unicode_data_path, "-u/--unicode-data-path");
  710. auto special_casing_file = open_file(special_casing_path, "-s/--special-casing-path");
  711. auto prop_list_file = open_file(prop_list_path, "-p/--prop-list-path");
  712. auto derived_core_prop_file = open_file(derived_core_prop_path, "-d/--derived-core-prop-path");
  713. auto derived_binary_prop_file = open_file(derived_binary_prop_path, "-b/--derived-binary-prop-path");
  714. auto prop_alias_file = open_file(prop_alias_path, "-a/--prop-alias-path");
  715. auto prop_value_alias_file = open_file(prop_value_alias_path, "-v/--prop-value-alias-path");
  716. auto scripts_file = open_file(scripts_path, "-r/--scripts-path");
  717. auto script_extensions_file = open_file(script_extensions_path, "-x/--script-extensions-path");
  718. auto word_break_file = open_file(word_break_path, "-w/--word-break-path");
  719. auto emoji_data_file = open_file(emoji_data_path, "-e/--emoji-data-path");
  720. UnicodeData unicode_data {};
  721. parse_special_casing(special_casing_file, unicode_data);
  722. parse_prop_list(prop_list_file, unicode_data.prop_list);
  723. parse_prop_list(derived_core_prop_file, unicode_data.prop_list);
  724. parse_prop_list(derived_binary_prop_file, unicode_data.prop_list);
  725. parse_prop_list(emoji_data_file, unicode_data.prop_list);
  726. parse_alias_list(prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases);
  727. parse_prop_list(scripts_file, unicode_data.script_list);
  728. parse_prop_list(script_extensions_file, unicode_data.script_extensions, true);
  729. parse_prop_list(word_break_file, unicode_data.word_break_prop_list);
  730. parse_unicode_data(unicode_data_file, unicode_data);
  731. parse_value_alias_list(prop_value_alias_file, "gc"sv, unicode_data.general_categories, unicode_data.general_category_unions, unicode_data.general_category_aliases);
  732. parse_value_alias_list(prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), {}, unicode_data.script_aliases, false);
  733. generate_unicode_data_header(generated_header_file, unicode_data);
  734. generate_unicode_data_implementation(generated_implementation_file, unicode_data);
  735. return 0;
  736. }