GenerateUnicodeData.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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/Find.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/Optional.h>
  12. #include <AK/QuickSort.h>
  13. #include <AK/SourceGenerator.h>
  14. #include <AK/String.h>
  15. #include <AK/StringUtils.h>
  16. #include <AK/Types.h>
  17. #include <AK/Vector.h>
  18. #include <LibCore/ArgsParser.h>
  19. #include <LibCore/File.h>
  20. // Some code points are excluded from UnicodeData.txt, and instead are part of a "range" of code
  21. // points, as indicated by the "name" field. For example:
  22. // 3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;
  23. // 4DBF;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;
  24. struct CodePointRange {
  25. u32 first;
  26. u32 last;
  27. };
  28. // SpecialCasing source: https://www.unicode.org/Public/13.0.0/ucd/SpecialCasing.txt
  29. // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#SpecialCasing.txt
  30. struct SpecialCasing {
  31. u32 index { 0 };
  32. u32 code_point { 0 };
  33. Vector<u32> lowercase_mapping;
  34. Vector<u32> uppercase_mapping;
  35. Vector<u32> titlecase_mapping;
  36. String locale;
  37. String condition;
  38. };
  39. // PropList source: https://www.unicode.org/Public/13.0.0/ucd/PropList.txt
  40. // Property descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#PropList.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. // Normalization source: https://www.unicode.org/Public/13.0.0/ucd/DerivedNormalizationProps.txt
  48. // Normalization descriptions: https://www.unicode.org/reports/tr44/#DerivedNormalizationProps.txt
  49. enum class QuickCheck {
  50. Yes,
  51. No,
  52. Maybe,
  53. };
  54. struct Normalization {
  55. CodePointRange code_point_range;
  56. Vector<u32> value;
  57. QuickCheck quick_check { QuickCheck::Yes };
  58. };
  59. using NormalizationProps = HashMap<String, Vector<Normalization>>;
  60. // UnicodeData source: https://www.unicode.org/Public/13.0.0/ucd/UnicodeData.txt
  61. // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#UnicodeData.txt
  62. // https://www.unicode.org/reports/tr44/#General_Category_Values
  63. struct CodePointData {
  64. u32 code_point { 0 };
  65. String name;
  66. u8 canonical_combining_class { 0 };
  67. String bidi_class;
  68. String decomposition_type;
  69. Optional<i8> numeric_value_decimal;
  70. Optional<i8> numeric_value_digit;
  71. Optional<i8> numeric_value_numeric;
  72. bool bidi_mirrored { false };
  73. String unicode_1_name;
  74. String iso_comment;
  75. Optional<u32> simple_uppercase_mapping;
  76. Optional<u32> simple_lowercase_mapping;
  77. Optional<u32> simple_titlecase_mapping;
  78. Vector<u32> special_casing_indices;
  79. };
  80. struct UnicodeData {
  81. Vector<SpecialCasing> special_casing;
  82. u32 largest_casing_transform_size { 0 };
  83. u32 largest_special_casing_size { 0 };
  84. Vector<String> conditions;
  85. Vector<CodePointData> code_point_data;
  86. Vector<CodePointRange> code_point_ranges;
  87. PropList general_categories;
  88. Vector<Alias> general_category_aliases;
  89. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  90. // any UCD file. Assigned code point ranges are derived as this generator is executed.
  91. // https://unicode.org/reports/tr18/#General_Category_Property
  92. PropList prop_list {
  93. { "Any"sv, { { 0, 0x10ffff } } },
  94. { "Assigned"sv, {} },
  95. { "ASCII"sv, { { 0, 0x7f } } },
  96. };
  97. Vector<Alias> prop_aliases;
  98. PropList script_list {
  99. { "Unknown"sv, {} },
  100. };
  101. Vector<Alias> script_aliases;
  102. PropList script_extensions;
  103. // FIXME: We are not yet doing anything with this data. It will be needed for String.prototype.normalize.
  104. NormalizationProps normalization_props;
  105. };
  106. static constexpr auto s_desired_fields = Array {
  107. "canonical_combining_class"sv,
  108. "simple_uppercase_mapping"sv,
  109. "simple_lowercase_mapping"sv,
  110. };
  111. static Vector<u32> parse_code_point_list(StringView const& list)
  112. {
  113. Vector<u32> code_points;
  114. auto segments = list.split_view(' ');
  115. for (auto const& code_point : segments)
  116. code_points.append(AK::StringUtils::convert_to_uint_from_hex<u32>(code_point).value());
  117. return code_points;
  118. }
  119. static CodePointRange parse_code_point_range(StringView const& list)
  120. {
  121. CodePointRange code_point_range {};
  122. if (list.contains(".."sv)) {
  123. auto segments = list.split_view(".."sv);
  124. VERIFY(segments.size() == 2);
  125. auto begin = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  126. auto end = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[1]).value();
  127. code_point_range = { begin, end };
  128. } else {
  129. auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(list).value();
  130. code_point_range = { code_point, code_point };
  131. }
  132. return code_point_range;
  133. }
  134. static void parse_special_casing(Core::File& file, UnicodeData& unicode_data)
  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.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  146. casing.lowercase_mapping = parse_code_point_list(segments[1]);
  147. casing.titlecase_mapping = parse_code_point_list(segments[2]);
  148. casing.uppercase_mapping = parse_code_point_list(segments[3]);
  149. if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) {
  150. auto conditions = condition.split(' ', true);
  151. VERIFY(conditions.size() == 1 || conditions.size() == 2);
  152. if (conditions.size() == 2) {
  153. casing.locale = move(conditions[0]);
  154. casing.condition = move(conditions[1]);
  155. } else if (all_of(conditions[0], is_ascii_lower_alpha)) {
  156. casing.locale = move(conditions[0]);
  157. } else {
  158. casing.condition = move(conditions[0]);
  159. }
  160. if (!casing.locale.is_empty())
  161. casing.locale = String::formatted("{:c}{}", to_ascii_uppercase(casing.locale[0]), casing.locale.substring_view(1));
  162. casing.condition = casing.condition.replace("_", "", true);
  163. if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
  164. unicode_data.conditions.append(casing.condition);
  165. }
  166. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.lowercase_mapping.size());
  167. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.titlecase_mapping.size());
  168. unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.uppercase_mapping.size());
  169. unicode_data.special_casing.append(move(casing));
  170. }
  171. quick_sort(unicode_data.special_casing, [](auto const& lhs, auto const& rhs) {
  172. if (lhs.code_point != rhs.code_point)
  173. return lhs.code_point < rhs.code_point;
  174. if (lhs.locale.is_empty() && !rhs.locale.is_empty())
  175. return false;
  176. if (!lhs.locale.is_empty() && rhs.locale.is_empty())
  177. return true;
  178. return lhs.locale < rhs.locale;
  179. });
  180. for (u32 i = 0; i < unicode_data.special_casing.size(); ++i)
  181. unicode_data.special_casing[i].index = i;
  182. }
  183. static void parse_prop_list(Core::File& file, PropList& prop_list, bool multi_value_property = false)
  184. {
  185. while (file.can_read_line()) {
  186. auto line = file.read_line();
  187. if (line.is_empty() || line.starts_with('#'))
  188. continue;
  189. if (auto index = line.find('#'); index.has_value())
  190. line = line.substring(0, *index);
  191. auto segments = line.split_view(';', true);
  192. VERIFY(segments.size() == 2);
  193. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  194. Vector<StringView> properties;
  195. if (multi_value_property)
  196. properties = segments[1].trim_whitespace().split_view(' ');
  197. else
  198. properties = { segments[1].trim_whitespace() };
  199. for (auto const& property : properties) {
  200. auto& code_points = prop_list.ensure(property.trim_whitespace());
  201. code_points.append(code_point_range);
  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>& 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))
  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_normalization_props(Core::File& file, UnicodeData& unicode_data)
  271. {
  272. while (file.can_read_line()) {
  273. auto line = file.read_line();
  274. if (line.is_empty() || line.starts_with('#'))
  275. continue;
  276. if (auto index = line.find('#'); index.has_value())
  277. line = line.substring(0, *index);
  278. auto segments = line.split_view(';', true);
  279. VERIFY((segments.size() == 2) || (segments.size() == 3));
  280. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  281. auto property = segments[1].trim_whitespace().to_string();
  282. Vector<u32> value;
  283. QuickCheck quick_check = QuickCheck::Yes;
  284. if (segments.size() == 3) {
  285. auto value_or_quick_check = segments[2].trim_whitespace();
  286. if ((value_or_quick_check == "N"sv))
  287. quick_check = QuickCheck::No;
  288. else if ((value_or_quick_check == "M"sv))
  289. quick_check = QuickCheck::Maybe;
  290. else
  291. value = parse_code_point_list(value_or_quick_check);
  292. }
  293. auto& normalizations = unicode_data.normalization_props.ensure(property);
  294. normalizations.append({ code_point_range, move(value), quick_check });
  295. auto& prop_list = unicode_data.prop_list.ensure(property);
  296. prop_list.append(move(code_point_range));
  297. }
  298. }
  299. static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data)
  300. {
  301. Optional<u32> code_point_range_start;
  302. auto& assigned_code_points = unicode_data.prop_list.find("Assigned"sv)->value;
  303. Optional<u32> assigned_code_point_range_start = 0;
  304. u32 previous_code_point = 0;
  305. while (file.can_read_line()) {
  306. auto line = file.read_line();
  307. if (line.is_empty())
  308. continue;
  309. auto segments = line.split(';', true);
  310. VERIFY(segments.size() == 15);
  311. CodePointData data {};
  312. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  313. data.name = move(segments[1]);
  314. data.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value();
  315. data.bidi_class = move(segments[4]);
  316. data.decomposition_type = move(segments[5]);
  317. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  318. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  319. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  320. data.bidi_mirrored = segments[9] == "Y"sv;
  321. data.unicode_1_name = move(segments[10]);
  322. data.iso_comment = move(segments[11]);
  323. data.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]);
  324. data.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]);
  325. data.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]);
  326. if (!assigned_code_point_range_start.has_value())
  327. assigned_code_point_range_start = data.code_point;
  328. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>")) {
  329. VERIFY(!code_point_range_start.has_value() && assigned_code_point_range_start.has_value());
  330. code_point_range_start = data.code_point;
  331. data.name = data.name.substring(1, data.name.length() - 9);
  332. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  333. assigned_code_point_range_start.clear();
  334. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>")) {
  335. VERIFY(code_point_range_start.has_value());
  336. CodePointRange code_point_range { *code_point_range_start, data.code_point };
  337. unicode_data.code_point_ranges.append(code_point_range);
  338. assigned_code_points.append(code_point_range);
  339. data.name = data.name.substring(1, data.name.length() - 8);
  340. code_point_range_start.clear();
  341. } else if ((data.code_point > 0) && (data.code_point - previous_code_point) != 1) {
  342. VERIFY(assigned_code_point_range_start.has_value());
  343. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  344. assigned_code_point_range_start = data.code_point;
  345. }
  346. for (auto const& casing : unicode_data.special_casing) {
  347. if (casing.code_point == data.code_point)
  348. data.special_casing_indices.append(casing.index);
  349. }
  350. unicode_data.largest_special_casing_size = max(unicode_data.largest_special_casing_size, data.special_casing_indices.size());
  351. previous_code_point = data.code_point;
  352. unicode_data.code_point_data.append(move(data));
  353. }
  354. }
  355. static void generate_unicode_data_header(Core::File& file, UnicodeData& unicode_data)
  356. {
  357. StringBuilder builder;
  358. SourceGenerator generator { builder };
  359. generator.set("casing_transform_size", String::number(unicode_data.largest_casing_transform_size));
  360. generator.set("special_casing_size", String::number(unicode_data.largest_special_casing_size));
  361. auto generate_enum = [&](StringView name, StringView default_, Vector<String> values, Vector<Alias> aliases = {}) {
  362. quick_sort(values);
  363. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  364. generator.set("name", name);
  365. generator.set("underlying", String::formatted("{}UnderlyingType", name));
  366. generator.append(R"~~~(
  367. using @underlying@ = u8;
  368. enum class @name@ : @underlying@ {)~~~");
  369. if (!default_.is_empty()) {
  370. generator.set("default", default_);
  371. generator.append(R"~~~(
  372. @default@,)~~~");
  373. }
  374. for (auto const& value : values) {
  375. generator.set("value", value);
  376. generator.append(R"~~~(
  377. @value@,)~~~");
  378. }
  379. for (auto const& alias : aliases) {
  380. generator.set("alias", alias.alias);
  381. generator.set("value", alias.property);
  382. generator.append(R"~~~(
  383. @alias@ = @value@,)~~~");
  384. }
  385. generator.append(R"~~~(
  386. };
  387. )~~~");
  388. };
  389. generator.append(R"~~~(
  390. #pragma once
  391. #include <AK/Optional.h>
  392. #include <AK/Types.h>
  393. #include <LibUnicode/Forward.h>
  394. #include <LibUnicode/UnicodeLocale.h>
  395. namespace Unicode {
  396. )~~~");
  397. generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions));
  398. generate_enum("GeneralCategory"sv, {}, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  399. generate_enum("Property"sv, {}, unicode_data.prop_list.keys(), unicode_data.prop_aliases);
  400. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), unicode_data.script_aliases);
  401. generator.append(R"~~~(
  402. struct SpecialCasing {
  403. u32 code_point { 0 };
  404. u32 lowercase_mapping[@casing_transform_size@];
  405. u32 lowercase_mapping_size { 0 };
  406. u32 uppercase_mapping[@casing_transform_size@];
  407. u32 uppercase_mapping_size { 0 };
  408. u32 titlecase_mapping[@casing_transform_size@];
  409. u32 titlecase_mapping_size { 0 };
  410. Locale locale { Locale::None };
  411. Condition condition { Condition::None };
  412. };
  413. struct UnicodeData {
  414. u32 code_point;)~~~");
  415. auto append_field = [&](StringView type, StringView name) {
  416. if (!s_desired_fields.span().contains_slow(name))
  417. return;
  418. generator.set("type", type);
  419. generator.set("name", name);
  420. generator.append(R"~~~(
  421. @type@ @name@;)~~~");
  422. };
  423. // Note: For compile-time performance, only primitive types are used.
  424. append_field("char const*"sv, "name"sv);
  425. append_field("u8"sv, "canonical_combining_class"sv);
  426. append_field("char const*"sv, "bidi_class"sv);
  427. append_field("char const*"sv, "decomposition_type"sv);
  428. append_field("i8"sv, "numeric_value_decimal"sv);
  429. append_field("i8"sv, "numeric_value_digit"sv);
  430. append_field("i8"sv, "numeric_value_numeric"sv);
  431. append_field("bool"sv, "bidi_mirrored"sv);
  432. append_field("char const*"sv, "unicode_1_name"sv);
  433. append_field("char const*"sv, "iso_comment"sv);
  434. append_field("u32"sv, "simple_uppercase_mapping"sv);
  435. append_field("u32"sv, "simple_lowercase_mapping"sv);
  436. append_field("u32"sv, "simple_titlecase_mapping"sv);
  437. generator.append(R"~~~(
  438. SpecialCasing const* special_casing[@special_casing_size@] {};
  439. u32 special_casing_size { 0 };
  440. };
  441. namespace Detail {
  442. Optional<UnicodeData> unicode_data_for_code_point(u32 code_point);
  443. bool code_point_has_general_category(u32 code_point, GeneralCategory general_category);
  444. Optional<GeneralCategory> general_category_from_string(StringView const& general_category);
  445. bool code_point_has_property(u32 code_point, Property property);
  446. Optional<Property> property_from_string(StringView const& property);
  447. bool code_point_has_script(u32 code_point, Script script);
  448. bool code_point_has_script_extension(u32 code_point, Script script);
  449. Optional<Script> script_from_string(StringView const& script);
  450. }
  451. }
  452. )~~~");
  453. file.write(generator.as_string_view());
  454. }
  455. static void generate_unicode_data_implementation(Core::File& file, UnicodeData const& unicode_data)
  456. {
  457. StringBuilder builder;
  458. SourceGenerator generator { builder };
  459. generator.set("special_casing_size", String::number(unicode_data.special_casing.size()));
  460. generator.set("code_point_data_size", String::number(unicode_data.code_point_data.size()));
  461. generator.append(R"~~~(
  462. #include <AK/Array.h>
  463. #include <AK/BinarySearch.h>
  464. #include <AK/CharacterTypes.h>
  465. #include <AK/HashMap.h>
  466. #include <AK/String.h>
  467. #include <AK/StringView.h>
  468. #include <LibUnicode/UnicodeData.h>
  469. namespace Unicode {
  470. )~~~");
  471. auto append_list_and_size = [&](auto const& list, StringView format) {
  472. if (list.is_empty()) {
  473. generator.append(", {}, 0");
  474. return;
  475. }
  476. bool first = true;
  477. generator.append(", {");
  478. for (auto const& item : list) {
  479. generator.append(first ? " " : ", ");
  480. generator.append(String::formatted(format, item));
  481. first = false;
  482. }
  483. generator.append(String::formatted(" }}, {}", list.size()));
  484. };
  485. generator.append(R"~~~(
  486. static constexpr Array<SpecialCasing, @special_casing_size@> s_special_casing { {)~~~");
  487. for (auto const& casing : unicode_data.special_casing) {
  488. generator.set("code_point", String::formatted("{:#x}", casing.code_point));
  489. generator.append(R"~~~(
  490. { @code_point@)~~~");
  491. constexpr auto format = "0x{:x}"sv;
  492. append_list_and_size(casing.lowercase_mapping, format);
  493. append_list_and_size(casing.uppercase_mapping, format);
  494. append_list_and_size(casing.titlecase_mapping, format);
  495. generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale);
  496. generator.append(", Locale::@locale@");
  497. generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition);
  498. generator.append(", Condition::@condition@");
  499. generator.append(" },");
  500. }
  501. generator.append(R"~~~(
  502. } };
  503. static constexpr Array<UnicodeData, @code_point_data_size@> s_unicode_data { {)~~~");
  504. auto append_field = [&](StringView name, String value) {
  505. if (!s_desired_fields.span().contains_slow(name))
  506. return;
  507. generator.set("value", move(value));
  508. generator.append(", @value@");
  509. };
  510. for (auto const& data : unicode_data.code_point_data) {
  511. generator.set("code_point", String::formatted("{:#x}", data.code_point));
  512. generator.append(R"~~~(
  513. { @code_point@)~~~");
  514. append_field("name", String::formatted("\"{}\"", data.name));
  515. append_field("canonical_combining_class", String::number(data.canonical_combining_class));
  516. append_field("bidi_class", String::formatted("\"{}\"", data.bidi_class));
  517. append_field("decomposition_type", String::formatted("\"{}\"", data.decomposition_type));
  518. append_field("numeric_value_decimal", String::number(data.numeric_value_decimal.value_or(-1)));
  519. append_field("numeric_value_digit", String::number(data.numeric_value_digit.value_or(-1)));
  520. append_field("numeric_value_numeric", String::number(data.numeric_value_numeric.value_or(-1)));
  521. append_field("bidi_mirrored", String::formatted("{}", data.bidi_mirrored));
  522. append_field("unicode_1_name", String::formatted("\"{}\"", data.unicode_1_name));
  523. append_field("iso_comment", String::formatted("\"{}\"", data.iso_comment));
  524. append_field("simple_uppercase_mapping", String::formatted("{:#x}", data.simple_uppercase_mapping.value_or(data.code_point)));
  525. append_field("simple_lowercase_mapping", String::formatted("{:#x}", data.simple_lowercase_mapping.value_or(data.code_point)));
  526. append_field("simple_titlecase_mapping", String::formatted("{:#x}", data.simple_titlecase_mapping.value_or(data.code_point)));
  527. append_list_and_size(data.special_casing_indices, "&s_special_casing[{}]"sv);
  528. generator.append(" },");
  529. }
  530. generator.append(R"~~~(
  531. } };
  532. struct CodePointRange {
  533. u32 first { 0 };
  534. u32 last { 0 };
  535. };
  536. struct CodePointRangeComparator {
  537. constexpr int operator()(u32 code_point, CodePointRange const& range)
  538. {
  539. return (code_point > range.last) - (code_point < range.first);
  540. }
  541. };
  542. )~~~");
  543. auto append_code_point_range_list = [&](String name, Vector<CodePointRange> const& ranges) {
  544. generator.set("name", name);
  545. generator.set("size", String::number(ranges.size()));
  546. generator.append(R"~~~(
  547. static constexpr Array<CodePointRange, @size@> @name@ { {
  548. )~~~");
  549. constexpr size_t max_ranges_per_row = 20;
  550. size_t ranges_in_current_row = 0;
  551. for (auto const& range : ranges) {
  552. if (ranges_in_current_row++ > 0)
  553. generator.append(" ");
  554. generator.set("first", String::formatted("{:#x}", range.first));
  555. generator.set("last", String::formatted("{:#x}", range.last));
  556. generator.append("{ @first@, @last@ },");
  557. if (ranges_in_current_row == max_ranges_per_row) {
  558. ranges_in_current_row = 0;
  559. generator.append("\n ");
  560. }
  561. }
  562. generator.append(R"~~~(
  563. } };
  564. )~~~");
  565. };
  566. auto append_prop_list = [&](StringView collection_name, StringView property_format, PropList const& property_list) {
  567. for (auto const& property : property_list) {
  568. auto name = String::formatted(property_format, property.key);
  569. append_code_point_range_list(move(name), property.value);
  570. }
  571. auto property_names = property_list.keys();
  572. quick_sort(property_names);
  573. generator.set("name", collection_name);
  574. generator.set("size", String::number(property_names.size()));
  575. generator.append(R"~~~(
  576. static constexpr Array<Span<CodePointRange const>, @size@> @name@ { {)~~~");
  577. for (auto const& property_name : property_names) {
  578. generator.set("name", String::formatted(property_format, property_name));
  579. generator.append(R"~~~(
  580. @name@.span(),)~~~");
  581. }
  582. generator.append(R"~~~(
  583. } };
  584. )~~~");
  585. };
  586. append_prop_list("s_general_categories"sv, "s_general_category_{}"sv, unicode_data.general_categories);
  587. append_prop_list("s_properties"sv, "s_property_{}"sv, unicode_data.prop_list);
  588. append_prop_list("s_scripts"sv, "s_script_{}"sv, unicode_data.script_list);
  589. append_prop_list("s_script_extensions"sv, "s_script_extension_{}"sv, unicode_data.script_extensions);
  590. generator.append(R"~~~(
  591. static HashMap<u32, UnicodeData const*> const& ensure_code_point_map()
  592. {
  593. static HashMap<u32, UnicodeData const*> code_point_to_data_map;
  594. code_point_to_data_map.ensure_capacity(s_unicode_data.size());
  595. for (auto const& unicode_data : s_unicode_data)
  596. code_point_to_data_map.set(unicode_data.code_point, &unicode_data);
  597. return code_point_to_data_map;
  598. }
  599. static Optional<u32> index_of_code_point_in_range(u32 code_point)
  600. {)~~~");
  601. for (auto const& range : unicode_data.code_point_ranges) {
  602. generator.set("first", String::formatted("{:#x}", range.first));
  603. generator.set("last", String::formatted("{:#x}", range.last));
  604. generator.append(R"~~~(
  605. if ((code_point > @first@) && (code_point < @last@))
  606. return @first@;)~~~");
  607. }
  608. generator.append(R"~~~(
  609. return {};
  610. }
  611. namespace Detail {
  612. Optional<UnicodeData> unicode_data_for_code_point(u32 code_point)
  613. {
  614. static auto const& code_point_to_data_map = ensure_code_point_map();
  615. VERIFY(is_unicode(code_point));
  616. if (auto data = code_point_to_data_map.get(code_point); data.has_value())
  617. return *(data.value());
  618. if (auto index = index_of_code_point_in_range(code_point); index.has_value()) {
  619. auto data_for_range = *(code_point_to_data_map.get(*index).value());
  620. data_for_range.simple_uppercase_mapping = code_point;
  621. data_for_range.simple_lowercase_mapping = code_point;
  622. return data_for_range;
  623. }
  624. return {};
  625. }
  626. )~~~");
  627. auto append_prop_search = [&](StringView enum_title, StringView enum_snake, StringView collection_name) {
  628. generator.set("enum_title", enum_title);
  629. generator.set("enum_snake", enum_snake);
  630. generator.set("collection_name", collection_name);
  631. generator.append(R"~~~(
  632. bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@)
  633. {
  634. auto index = static_cast<@enum_title@UnderlyingType>(@enum_snake@);
  635. auto const& ranges = @collection_name@.at(index);
  636. auto const* range = binary_search(ranges, code_point, nullptr, CodePointRangeComparator {});
  637. return range != nullptr;
  638. }
  639. )~~~");
  640. };
  641. auto append_from_string = [&](StringView enum_title, StringView enum_snake, PropList const& prop_list, Vector<Alias> const& aliases) {
  642. generator.set("enum_title", enum_title);
  643. generator.set("enum_snake", enum_snake);
  644. auto properties = prop_list.keys();
  645. for (auto const& alias : aliases)
  646. properties.append(alias.alias);
  647. quick_sort(properties);
  648. generator.append(R"~~~(
  649. Optional<@enum_title@> @enum_snake@_from_string(StringView const& @enum_snake@)
  650. {
  651. static HashMap<String, @enum_title@> @enum_snake@_values { {)~~~");
  652. for (auto const& property : properties) {
  653. generator.set("property", property);
  654. generator.append(R"~~~(
  655. { "@property@"sv, @enum_title@::@property@ },)~~~");
  656. }
  657. generator.append(R"~~~(
  658. } };
  659. if (auto value = @enum_snake@_values.get(@enum_snake@); value.has_value())
  660. return value.value();
  661. return {};
  662. }
  663. )~~~");
  664. };
  665. append_prop_search("GeneralCategory"sv, "general_category"sv, "s_general_categories"sv);
  666. append_from_string("GeneralCategory"sv, "general_category"sv, unicode_data.general_categories, unicode_data.general_category_aliases);
  667. append_prop_search("Property"sv, "property"sv, "s_properties"sv);
  668. append_from_string("Property"sv, "property"sv, unicode_data.prop_list, unicode_data.prop_aliases);
  669. append_prop_search("Script"sv, "script"sv, "s_scripts"sv);
  670. append_prop_search("Script"sv, "script_extension"sv, "s_script_extensions"sv);
  671. append_from_string("Script"sv, "script"sv, unicode_data.script_list, unicode_data.script_aliases);
  672. generator.append(R"~~~(
  673. }
  674. }
  675. )~~~");
  676. file.write(generator.as_string_view());
  677. }
  678. static Vector<u32> flatten_code_point_ranges(Vector<CodePointRange> const& code_points)
  679. {
  680. Vector<u32> flattened;
  681. for (auto const& range : code_points) {
  682. flattened.grow_capacity(range.last - range.first);
  683. for (u32 code_point = range.first; code_point <= range.last; ++code_point)
  684. flattened.append(code_point);
  685. }
  686. return flattened;
  687. }
  688. static Vector<CodePointRange> form_code_point_ranges(Vector<u32> code_points)
  689. {
  690. Vector<CodePointRange> ranges;
  691. u32 range_start = code_points[0];
  692. u32 range_end = range_start;
  693. for (size_t i = 1; i < code_points.size(); ++i) {
  694. u32 code_point = code_points[i];
  695. if ((code_point - range_end) == 1) {
  696. range_end = code_point;
  697. } else {
  698. ranges.append({ range_start, range_end });
  699. range_start = code_point;
  700. range_end = code_point;
  701. }
  702. }
  703. ranges.append({ range_start, range_end });
  704. return ranges;
  705. }
  706. static void sort_and_merge_code_point_ranges(Vector<CodePointRange>& code_points)
  707. {
  708. quick_sort(code_points, [](auto const& range1, auto const& range2) {
  709. return range1.first < range2.first;
  710. });
  711. for (size_t i = 0; i < code_points.size() - 1;) {
  712. if (code_points[i].last >= code_points[i + 1].first) {
  713. code_points[i].last = max(code_points[i].last, code_points[i + 1].last);
  714. code_points.remove(i + 1);
  715. } else {
  716. ++i;
  717. }
  718. }
  719. auto all_code_points = flatten_code_point_ranges(code_points);
  720. code_points = form_code_point_ranges(all_code_points);
  721. }
  722. static void populate_general_category_unions(PropList& general_categories)
  723. {
  724. // The Unicode standard defines General Category values which are not in any UCD file. These
  725. // values are simply unions of other values.
  726. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  727. auto populate_union = [&](auto alias, auto categories) {
  728. auto& code_points = general_categories.ensure(alias);
  729. for (auto const& category : categories)
  730. code_points.extend(general_categories.find(category)->value);
  731. sort_and_merge_code_point_ranges(code_points);
  732. };
  733. populate_union("LC"sv, Array { "Ll"sv, "Lu"sv, "Lt"sv });
  734. populate_union("L"sv, Array { "Lu"sv, "Ll"sv, "Lt"sv, "Lm"sv, "Lo"sv });
  735. populate_union("M"sv, Array { "Mn"sv, "Mc"sv, "Me"sv });
  736. populate_union("N"sv, Array { "Nd"sv, "Nl"sv, "No"sv });
  737. populate_union("P"sv, Array { "Pc"sv, "Pd"sv, "Ps"sv, "Pe"sv, "Pi"sv, "Pf"sv, "Po"sv });
  738. populate_union("S"sv, Array { "Sm"sv, "Sc"sv, "Sk"sv, "So"sv });
  739. populate_union("Z"sv, Array { "Zs"sv, "Zl"sv, "Zp"sv });
  740. populate_union("C"sv, Array { "Cc"sv, "Cf"sv, "Cs"sv, "Co"sv, "Cn"sv });
  741. }
  742. static void normalize_script_extensions(PropList& script_extensions, PropList const& script_list, Vector<Alias> const& script_aliases)
  743. {
  744. // The ScriptExtensions UCD file lays out its code point ranges rather uniquely compared to
  745. // other files. The Script listed on each line may either be a full Script string or an aliased
  746. // abbreviation. Further, the extensions may or may not include the base Script list. Normalize
  747. // the extensions here to be keyed by the full Script name and always include the base list.
  748. auto extensions = move(script_extensions);
  749. script_extensions = script_list;
  750. for (auto const& extension : extensions) {
  751. auto it = find_if(script_aliases.begin(), script_aliases.end(), [&](auto const& alias) { return extension.key == alias.alias; });
  752. auto const& key = (it == script_aliases.end()) ? extension.key : it->property;
  753. auto& code_points = script_extensions.find(key)->value;
  754. code_points.extend(extension.value);
  755. sort_and_merge_code_point_ranges(code_points);
  756. }
  757. // Lastly, the Common and Inherited script extensions are special. They must not contain any
  758. // code points which appear in other script extensions. The ScriptExtensions UCD file does not
  759. // list these extensions, therefore this peculiarity must be handled programatically.
  760. // https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values
  761. auto code_point_has_other_extension = [&](StringView key, u32 code_point) {
  762. for (auto const& extension : extensions) {
  763. if (extension.key == key)
  764. continue;
  765. if (any_of(extension.value, [&](auto const& r) { return (r.first <= code_point) && (code_point <= r.last); }))
  766. return true;
  767. }
  768. return false;
  769. };
  770. auto get_code_points_without_other_extensions = [&](StringView key) {
  771. auto code_points = flatten_code_point_ranges(script_list.find(key)->value);
  772. code_points.remove_all_matching([&](u32 c) { return code_point_has_other_extension(key, c); });
  773. return code_points;
  774. };
  775. auto common_code_points = get_code_points_without_other_extensions("Common"sv);
  776. script_extensions.set("Common"sv, form_code_point_ranges(common_code_points));
  777. auto inherited_code_points = get_code_points_without_other_extensions("Inherited"sv);
  778. script_extensions.set("Inherited"sv, form_code_point_ranges(inherited_code_points));
  779. }
  780. int main(int argc, char** argv)
  781. {
  782. char const* generated_header_path = nullptr;
  783. char const* generated_implementation_path = nullptr;
  784. char const* unicode_data_path = nullptr;
  785. char const* special_casing_path = nullptr;
  786. char const* derived_general_category_path = nullptr;
  787. char const* prop_list_path = nullptr;
  788. char const* derived_core_prop_path = nullptr;
  789. char const* derived_binary_prop_path = nullptr;
  790. char const* prop_alias_path = nullptr;
  791. char const* prop_value_alias_path = nullptr;
  792. char const* scripts_path = nullptr;
  793. char const* script_extensions_path = nullptr;
  794. char const* emoji_data_path = nullptr;
  795. char const* normalization_path = nullptr;
  796. Core::ArgsParser args_parser;
  797. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  798. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  799. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  800. args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path");
  801. args_parser.add_option(derived_general_category_path, "Path to DerivedGeneralCategory.txt file", "derived-general-category-path", 'g', "derived-general-category-path");
  802. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  803. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  804. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  805. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  806. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  807. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  808. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  809. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  810. args_parser.add_option(normalization_path, "Path to DerivedNormalizationProps.txt file", "normalization-path", 'n', "normalization-path");
  811. args_parser.parse(argc, argv);
  812. auto open_file = [&](StringView path, StringView flags, Core::OpenMode mode = Core::OpenMode::ReadOnly) {
  813. if (path.is_empty()) {
  814. warnln("{} is required", flags);
  815. args_parser.print_usage(stderr, argv[0]);
  816. exit(1);
  817. }
  818. auto file_or_error = Core::File::open(path, mode);
  819. if (file_or_error.is_error()) {
  820. warnln("Failed to open {}: {}", path, file_or_error.release_error());
  821. exit(1);
  822. }
  823. return file_or_error.release_value();
  824. };
  825. auto generated_header_file = open_file(generated_header_path, "-h/--generated-header-path", Core::OpenMode::ReadWrite);
  826. auto generated_implementation_file = open_file(generated_implementation_path, "-c/--generated-implementation-path", Core::OpenMode::ReadWrite);
  827. auto unicode_data_file = open_file(unicode_data_path, "-u/--unicode-data-path");
  828. auto derived_general_category_file = open_file(derived_general_category_path, "-g/--derived-general-category-path");
  829. auto special_casing_file = open_file(special_casing_path, "-s/--special-casing-path");
  830. auto prop_list_file = open_file(prop_list_path, "-p/--prop-list-path");
  831. auto derived_core_prop_file = open_file(derived_core_prop_path, "-d/--derived-core-prop-path");
  832. auto derived_binary_prop_file = open_file(derived_binary_prop_path, "-b/--derived-binary-prop-path");
  833. auto prop_alias_file = open_file(prop_alias_path, "-a/--prop-alias-path");
  834. auto prop_value_alias_file = open_file(prop_value_alias_path, "-v/--prop-value-alias-path");
  835. auto scripts_file = open_file(scripts_path, "-r/--scripts-path");
  836. auto script_extensions_file = open_file(script_extensions_path, "-x/--script-extensions-path");
  837. auto emoji_data_file = open_file(emoji_data_path, "-e/--emoji-data-path");
  838. auto normalization_file = open_file(normalization_path, "-n/--normalization-path");
  839. UnicodeData unicode_data {};
  840. parse_special_casing(special_casing_file, unicode_data);
  841. parse_prop_list(derived_general_category_file, unicode_data.general_categories);
  842. parse_prop_list(prop_list_file, unicode_data.prop_list);
  843. parse_prop_list(derived_core_prop_file, unicode_data.prop_list);
  844. parse_prop_list(derived_binary_prop_file, unicode_data.prop_list);
  845. parse_prop_list(emoji_data_file, unicode_data.prop_list);
  846. parse_normalization_props(normalization_file, unicode_data);
  847. parse_alias_list(prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases);
  848. parse_prop_list(scripts_file, unicode_data.script_list);
  849. parse_prop_list(script_extensions_file, unicode_data.script_extensions, true);
  850. populate_general_category_unions(unicode_data.general_categories);
  851. parse_unicode_data(unicode_data_file, unicode_data);
  852. parse_value_alias_list(prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  853. parse_value_alias_list(prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false);
  854. normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases);
  855. generate_unicode_data_header(generated_header_file, unicode_data);
  856. generate_unicode_data_implementation(generated_implementation_file, unicode_data);
  857. return 0;
  858. }