GenerateUnicodeData.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "GeneratorUtil.h"
  7. #include <AK/AllOf.h>
  8. #include <AK/Array.h>
  9. #include <AK/ByteString.h>
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/Error.h>
  12. #include <AK/Find.h>
  13. #include <AK/HashMap.h>
  14. #include <AK/Optional.h>
  15. #include <AK/QuickSort.h>
  16. #include <AK/SourceGenerator.h>
  17. #include <AK/StringUtils.h>
  18. #include <AK/Types.h>
  19. #include <AK/Vector.h>
  20. #include <LibCore/ArgsParser.h>
  21. #include <LibUnicode/CharacterTypes.h>
  22. // https://www.unicode.org/reports/tr44/#PropList.txt
  23. using PropList = HashMap<ByteString, Vector<Unicode::CodePointRange>>;
  24. // https://www.unicode.org/reports/tr44/#DerivedNormalizationProps.txt
  25. enum class QuickCheck {
  26. Yes,
  27. No,
  28. Maybe,
  29. };
  30. struct Normalization {
  31. Unicode::CodePointRange code_point_range;
  32. Vector<u32> value;
  33. QuickCheck quick_check { QuickCheck::Yes };
  34. };
  35. using NormalizationProps = HashMap<ByteString, Vector<Normalization>>;
  36. // https://www.unicode.org/reports/tr44/#UnicodeData.txt
  37. struct CodePointData {
  38. u32 code_point { 0 };
  39. ByteString name;
  40. ByteString bidi_class;
  41. Optional<i8> numeric_value_decimal;
  42. Optional<i8> numeric_value_digit;
  43. Optional<i8> numeric_value_numeric;
  44. bool bidi_mirrored { false };
  45. ByteString unicode_1_name;
  46. ByteString iso_comment;
  47. };
  48. using PropertyTable = Vector<bool>;
  49. static constexpr auto CODE_POINT_TABLES_MSB_COUNT = 16u;
  50. static_assert(CODE_POINT_TABLES_MSB_COUNT < 24u);
  51. static constexpr auto CODE_POINT_TABLES_LSB_COUNT = 24u - CODE_POINT_TABLES_MSB_COUNT;
  52. static constexpr auto CODE_POINT_TABLES_LSB_MASK = NumericLimits<u32>::max() >> (NumericLimits<u32>::digits() - CODE_POINT_TABLES_LSB_COUNT);
  53. template<typename PropertyType>
  54. struct CodePointTables {
  55. Vector<size_t> stage1;
  56. Vector<size_t> stage2;
  57. Vector<PropertyType> unique_properties;
  58. };
  59. struct CodePointBidiClass {
  60. Unicode::CodePointRange code_point_range;
  61. ByteString bidi_class;
  62. };
  63. struct UnicodeData {
  64. Vector<CodePointData> code_point_data;
  65. // https://www.unicode.org/reports/tr44/#General_Category_Values
  66. PropList general_categories;
  67. Vector<Alias> general_category_aliases;
  68. // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in
  69. // any UCD file. Assigned code point ranges are derived as this generator is executed.
  70. // https://unicode.org/reports/tr18/#General_Category_Property
  71. PropList prop_list {
  72. { "Any"sv, { { 0, 0x10ffff } } },
  73. { "Assigned"sv, {} },
  74. { "ASCII"sv, { { 0, 0x7f } } },
  75. };
  76. Vector<Alias> prop_aliases;
  77. PropList script_list {
  78. { "Unknown"sv, {} },
  79. };
  80. Vector<Alias> script_aliases;
  81. PropList script_extensions;
  82. // FIXME: We are not yet doing anything with this data. It will be needed for String.prototype.normalize.
  83. NormalizationProps normalization_props;
  84. CodePointTables<PropertyTable> general_category_tables;
  85. CodePointTables<PropertyTable> property_tables;
  86. CodePointTables<PropertyTable> script_tables;
  87. CodePointTables<PropertyTable> script_extension_tables;
  88. HashTable<ByteString> bidirectional_classes;
  89. Vector<CodePointBidiClass> code_point_bidirectional_classes;
  90. };
  91. static ByteString sanitize_entry(ByteString const& entry)
  92. {
  93. auto sanitized = entry.replace("-"sv, "_"sv, ReplaceMode::All);
  94. sanitized = sanitized.replace(" "sv, "_"sv, ReplaceMode::All);
  95. StringBuilder builder;
  96. bool next_is_upper = true;
  97. for (auto ch : sanitized) {
  98. if (next_is_upper)
  99. builder.append_code_point(to_ascii_uppercase(ch));
  100. else
  101. builder.append_code_point(ch);
  102. next_is_upper = ch == '_';
  103. }
  104. return builder.to_byte_string();
  105. }
  106. static ErrorOr<void> parse_prop_list(Core::InputBufferedFile& file, PropList& prop_list, bool multi_value_property = false, bool sanitize_property = false)
  107. {
  108. Array<u8, 1024> buffer;
  109. while (TRY(file.can_read_line())) {
  110. auto line = TRY(file.read_line(buffer));
  111. if (line.is_empty() || line.starts_with('#'))
  112. continue;
  113. if (auto index = line.find('#'); index.has_value())
  114. line = line.substring_view(0, *index);
  115. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  116. VERIFY(segments.size() == 2 || segments.size() == 3);
  117. String combined_segment_buffer;
  118. if (segments.size() == 3) {
  119. // For example, in DerivedCoreProperties.txt, there are lines such as:
  120. //
  121. // 094D ; InCB; Linker # Mn DEVANAGARI SIGN VIRAMA
  122. //
  123. // These are used in text segmentation to prevent breaking within some extended grapheme clusters.
  124. // So here, we combine the segments into a single property, which allows us to simply do code point
  125. // property lookups at runtime for specific Indic Conjunct Break sequences.
  126. combined_segment_buffer = MUST(String::join('_', Array { segments[1].trim_whitespace(), segments[2].trim_whitespace() }));
  127. segments[1] = combined_segment_buffer;
  128. }
  129. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  130. Vector<StringView> properties;
  131. if (multi_value_property)
  132. properties = segments[1].trim_whitespace().split_view(' ');
  133. else
  134. properties = { segments[1].trim_whitespace() };
  135. for (auto& property : properties) {
  136. auto& code_points = prop_list.ensure(sanitize_property ? sanitize_entry(property).trim_whitespace() : ByteString { property.trim_whitespace() });
  137. code_points.append(code_point_range);
  138. }
  139. }
  140. return {};
  141. }
  142. static ErrorOr<void> parse_alias_list(Core::InputBufferedFile& file, PropList const& prop_list, Vector<Alias>& prop_aliases)
  143. {
  144. ByteString current_property;
  145. Array<u8, 1024> buffer;
  146. auto append_alias = [&](auto alias, auto property) {
  147. // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip.
  148. if (alias == property)
  149. return;
  150. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  151. if (!prop_list.contains(property))
  152. return;
  153. prop_aliases.append({ property, alias });
  154. };
  155. while (TRY(file.can_read_line())) {
  156. auto line = TRY(file.read_line(buffer));
  157. if (line.is_empty() || line.starts_with('#')) {
  158. if (line.ends_with("Properties"sv))
  159. current_property = line.substring_view(2);
  160. continue;
  161. }
  162. // Note: For now, we only care about Binary Property aliases for Unicode property escapes.
  163. if (current_property != "Binary Properties"sv)
  164. continue;
  165. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  166. VERIFY((segments.size() == 2) || (segments.size() == 3));
  167. auto alias = segments[0].trim_whitespace();
  168. auto property = segments[1].trim_whitespace();
  169. append_alias(alias, property);
  170. if (segments.size() == 3) {
  171. alias = segments[2].trim_whitespace();
  172. append_alias(alias, property);
  173. }
  174. }
  175. return {};
  176. }
  177. static ErrorOr<void> parse_value_alias_list(Core::InputBufferedFile& file, StringView desired_category, Vector<ByteString> const& value_list, Vector<Alias>& prop_aliases, bool primary_value_is_first = true, bool sanitize_alias = false)
  178. {
  179. TRY(file.seek(0, SeekMode::SetPosition));
  180. Array<u8, 1024> buffer;
  181. auto append_alias = [&](auto alias, auto value) {
  182. // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip.
  183. if (alias == value)
  184. return;
  185. // FIXME: We will, eventually, need to find where missing properties are located and parse them.
  186. if (!value_list.contains_slow(value))
  187. return;
  188. prop_aliases.append({ value, alias });
  189. };
  190. while (TRY(file.can_read_line())) {
  191. auto line = TRY(file.read_line(buffer));
  192. if (line.is_empty() || line.starts_with('#'))
  193. continue;
  194. if (auto index = line.find('#'); index.has_value())
  195. line = line.substring_view(0, *index);
  196. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  197. auto category = segments[0].trim_whitespace();
  198. if (category != desired_category)
  199. continue;
  200. VERIFY((segments.size() == 3) || (segments.size() == 4));
  201. auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace();
  202. auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace();
  203. append_alias(sanitize_alias ? sanitize_entry(alias) : ByteString { alias }, value);
  204. if (segments.size() == 4) {
  205. alias = segments[3].trim_whitespace();
  206. append_alias(sanitize_alias ? sanitize_entry(alias) : ByteString { alias }, value);
  207. }
  208. }
  209. return {};
  210. }
  211. static ErrorOr<void> parse_normalization_props(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  212. {
  213. Array<u8, 1024> buffer;
  214. while (TRY(file.can_read_line())) {
  215. auto line = TRY(file.read_line(buffer));
  216. if (line.is_empty() || line.starts_with('#'))
  217. continue;
  218. if (auto index = line.find('#'); index.has_value())
  219. line = line.substring_view(0, *index);
  220. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  221. VERIFY((segments.size() == 2) || (segments.size() == 3));
  222. auto code_point_range = parse_code_point_range(segments[0].trim_whitespace());
  223. auto property = segments[1].trim_whitespace().to_byte_string();
  224. Vector<u32> value;
  225. QuickCheck quick_check = QuickCheck::Yes;
  226. if (segments.size() == 3) {
  227. auto value_or_quick_check = segments[2].trim_whitespace();
  228. if ((value_or_quick_check == "N"sv))
  229. quick_check = QuickCheck::No;
  230. else if ((value_or_quick_check == "M"sv))
  231. quick_check = QuickCheck::Maybe;
  232. else
  233. value = parse_code_point_list(value_or_quick_check);
  234. }
  235. auto& normalizations = unicode_data.normalization_props.ensure(property);
  236. normalizations.append({ code_point_range, move(value), quick_check });
  237. auto& prop_list = unicode_data.prop_list.ensure(property);
  238. prop_list.append(move(code_point_range));
  239. }
  240. return {};
  241. }
  242. static ErrorOr<void> parse_unicode_data(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  243. {
  244. Optional<u32> code_point_range_start;
  245. auto& assigned_code_points = unicode_data.prop_list.find("Assigned"sv)->value;
  246. Optional<u32> assigned_code_point_range_start = 0;
  247. u32 previous_code_point = 0;
  248. Array<u8, 1024> buffer;
  249. while (TRY(file.can_read_line())) {
  250. auto line = TRY(file.read_line(buffer));
  251. if (line.is_empty())
  252. continue;
  253. auto segments = line.split_view(';', SplitBehavior::KeepEmpty);
  254. VERIFY(segments.size() == 15);
  255. CodePointData data {};
  256. data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value();
  257. data.name = segments[1];
  258. data.bidi_class = segments[4];
  259. data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]);
  260. data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]);
  261. data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]);
  262. data.bidi_mirrored = segments[9] == "Y"sv;
  263. data.unicode_1_name = segments[10];
  264. data.iso_comment = segments[11];
  265. if (!assigned_code_point_range_start.has_value())
  266. assigned_code_point_range_start = data.code_point;
  267. if (data.name.starts_with("<"sv) && data.name.ends_with(", First>"sv)) {
  268. VERIFY(!code_point_range_start.has_value() && assigned_code_point_range_start.has_value());
  269. code_point_range_start = data.code_point;
  270. data.name = data.name.substring(1, data.name.length() - 9);
  271. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  272. assigned_code_point_range_start.clear();
  273. } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>"sv)) {
  274. VERIFY(code_point_range_start.has_value());
  275. Unicode::CodePointRange code_point_range { *code_point_range_start, data.code_point };
  276. assigned_code_points.append(code_point_range);
  277. data.name = data.name.substring(1, data.name.length() - 8);
  278. code_point_range_start.clear();
  279. unicode_data.code_point_bidirectional_classes.append({ code_point_range, data.bidi_class });
  280. } else {
  281. unicode_data.code_point_bidirectional_classes.append({ { data.code_point, data.code_point }, data.bidi_class });
  282. if ((data.code_point > 0) && (data.code_point - previous_code_point) != 1) {
  283. VERIFY(assigned_code_point_range_start.has_value());
  284. assigned_code_points.append({ *assigned_code_point_range_start, previous_code_point });
  285. assigned_code_point_range_start = data.code_point;
  286. }
  287. }
  288. unicode_data.bidirectional_classes.set(data.bidi_class, AK::HashSetExistingEntryBehavior::Keep);
  289. previous_code_point = data.code_point;
  290. unicode_data.code_point_data.append(move(data));
  291. }
  292. return {};
  293. }
  294. static ErrorOr<void> generate_unicode_data_header(Core::InputBufferedFile& file, UnicodeData& unicode_data)
  295. {
  296. StringBuilder builder;
  297. SourceGenerator generator { builder };
  298. auto generate_enum = [&](StringView name, StringView default_, auto values, Vector<Alias> aliases = {}) {
  299. quick_sort(values);
  300. quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; });
  301. generator.set("name", name);
  302. generator.set("underlying", ByteString::formatted("{}UnderlyingType", name));
  303. generator.set("type", ((values.size() + !default_.is_empty()) < 256) ? "u8"sv : "u16"sv);
  304. generator.append(R"~~~(
  305. using @underlying@ = @type@;
  306. enum class @name@ : @underlying@ {)~~~");
  307. if (!default_.is_empty()) {
  308. generator.set("default", default_);
  309. generator.append(R"~~~(
  310. @default@,)~~~");
  311. }
  312. for (auto const& value : values) {
  313. generator.set("value", value);
  314. generator.append(R"~~~(
  315. @value@,)~~~");
  316. }
  317. for (auto const& alias : aliases) {
  318. generator.set("alias", alias.alias);
  319. generator.set("value", alias.name);
  320. generator.append(R"~~~(
  321. @alias@ = @value@,)~~~");
  322. }
  323. generator.append(R"~~~(
  324. };
  325. )~~~");
  326. };
  327. generator.append(R"~~~(
  328. #pragma once
  329. #include <AK/Types.h>
  330. #include <LibUnicode/Forward.h>
  331. namespace Unicode {
  332. )~~~");
  333. generate_enum("GeneralCategory"sv, {}, unicode_data.general_categories.keys(), unicode_data.general_category_aliases);
  334. generate_enum("Property"sv, {}, unicode_data.prop_list.keys(), unicode_data.prop_aliases);
  335. generate_enum("Script"sv, {}, unicode_data.script_list.keys(), unicode_data.script_aliases);
  336. generate_enum("BidirectionalClass"sv, {}, unicode_data.bidirectional_classes.values());
  337. generator.append(R"~~~(
  338. }
  339. )~~~");
  340. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  341. return {};
  342. }
  343. static ErrorOr<void> generate_unicode_data_implementation(Core::InputBufferedFile& file, UnicodeData const& unicode_data)
  344. {
  345. StringBuilder builder;
  346. SourceGenerator generator { builder };
  347. generator.set("CODE_POINT_TABLES_LSB_COUNT", TRY(String::number(CODE_POINT_TABLES_LSB_COUNT)));
  348. generator.set("CODE_POINT_TABLES_LSB_MASK", TRY(String::formatted("{:#x}", CODE_POINT_TABLES_LSB_MASK)));
  349. generator.append(R"~~~(
  350. #include <AK/Array.h>
  351. #include <AK/BinarySearch.h>
  352. #include <AK/CharacterTypes.h>
  353. #include <AK/Optional.h>
  354. #include <AK/Span.h>
  355. #include <AK/ByteString.h>
  356. #include <AK/StringView.h>
  357. #include <LibUnicode/CharacterTypes.h>
  358. #include <LibUnicode/UnicodeData.h>
  359. #include <LibUnicode/Normalize.h>
  360. namespace Unicode {
  361. )~~~");
  362. generator.append(R"~~~(
  363. struct BidiClassData {
  364. CodePointRange code_point_range {};
  365. BidirectionalClass bidi_class {};
  366. };
  367. struct CodePointBidiClassComparator : public CodePointRangeComparator {
  368. constexpr int operator()(u32 code_point, BidiClassData const& bidi_class)
  369. {
  370. return CodePointRangeComparator::operator()(code_point, bidi_class.code_point_range);
  371. }
  372. };
  373. )~~~");
  374. auto append_property_table = [&](auto collection_snake, auto const& unique_properties) -> ErrorOr<void> {
  375. generator.set("name", TRY(String::formatted("{}_unique_properties", collection_snake)));
  376. generator.set("outer_size", TRY(String::number(unique_properties.size())));
  377. generator.set("inner_size", TRY(String::number(unique_properties[0].size())));
  378. generator.append(R"~~~(
  379. static constexpr Array<Array<bool, @inner_size@>, @outer_size@> @name@ { {)~~~");
  380. for (auto const& property_set : unique_properties) {
  381. generator.append(R"~~~(
  382. { )~~~");
  383. for (auto value : property_set) {
  384. generator.set("value", TRY(String::formatted("{}", value)));
  385. generator.append("@value@, ");
  386. }
  387. generator.append(" },");
  388. }
  389. generator.append(R"~~~(
  390. } };
  391. )~~~");
  392. return {};
  393. };
  394. auto append_code_point_tables = [&](StringView collection_snake, auto const& tables, auto& append_unique_properties) -> ErrorOr<void> {
  395. auto append_stage = [&](auto const& stage, auto name, auto type) -> ErrorOr<void> {
  396. generator.set("name", TRY(String::formatted("{}_{}", collection_snake, name)));
  397. generator.set("size", TRY(String::number(stage.size())));
  398. generator.set("type", type);
  399. generator.append(R"~~~(
  400. static constexpr Array<@type@, @size@> @name@ { {
  401. )~~~");
  402. static constexpr size_t max_values_per_row = 300;
  403. size_t values_in_current_row = 0;
  404. for (auto value : stage) {
  405. if (values_in_current_row++ > 0)
  406. generator.append(", ");
  407. generator.set("value", TRY(String::number(value)));
  408. generator.append("@value@");
  409. if (values_in_current_row == max_values_per_row) {
  410. values_in_current_row = 0;
  411. generator.append(",\n ");
  412. }
  413. }
  414. generator.append(R"~~~(
  415. } };
  416. )~~~");
  417. return {};
  418. };
  419. TRY(append_stage(tables.stage1, "stage1"sv, "u16"sv));
  420. TRY(append_stage(tables.stage2, "stage2"sv, "u16"sv));
  421. TRY(append_unique_properties(collection_snake, tables.unique_properties));
  422. return {};
  423. };
  424. TRY(append_code_point_tables("s_general_categories"sv, unicode_data.general_category_tables, append_property_table));
  425. TRY(append_code_point_tables("s_properties"sv, unicode_data.property_tables, append_property_table));
  426. TRY(append_code_point_tables("s_scripts"sv, unicode_data.script_tables, append_property_table));
  427. TRY(append_code_point_tables("s_script_extensions"sv, unicode_data.script_extension_tables, append_property_table));
  428. {
  429. constexpr size_t max_bidi_classes_per_row = 20;
  430. size_t bidi_classes_in_current_row = 0;
  431. generator.set("size"sv, ByteString::number(unicode_data.code_point_bidirectional_classes.size()));
  432. generator.append(R"~~~(
  433. static constexpr Array<BidiClassData, @size@> s_bidirectional_classes { {
  434. )~~~");
  435. for (auto const& data : unicode_data.code_point_bidirectional_classes) {
  436. if (bidi_classes_in_current_row++ > 0)
  437. generator.append(", ");
  438. generator.set("first", ByteString::formatted("{:#x}", data.code_point_range.first));
  439. generator.set("last", ByteString::formatted("{:#x}", data.code_point_range.last));
  440. generator.set("bidi_class", data.bidi_class);
  441. generator.append("{ { @first@, @last@ }, BidirectionalClass::@bidi_class@ }");
  442. if (bidi_classes_in_current_row == max_bidi_classes_per_row) {
  443. bidi_classes_in_current_row = 0;
  444. generator.append(",\n ");
  445. }
  446. }
  447. generator.append(R"~~~(
  448. } };
  449. )~~~");
  450. }
  451. generator.append(R"~~~(
  452. Optional<BidirectionalClass> bidirectional_class(u32 code_point)
  453. {
  454. if (auto const* entry = binary_search(s_bidirectional_classes, code_point, nullptr, CodePointBidiClassComparator {}))
  455. return entry->bidi_class;
  456. return {};
  457. }
  458. )~~~");
  459. auto append_prop_search = [&](StringView enum_title, StringView enum_snake, StringView collection_name) -> ErrorOr<void> {
  460. generator.set("enum_title", enum_title);
  461. generator.set("enum_snake", enum_snake);
  462. generator.set("collection_name", collection_name);
  463. generator.append(R"~~~(
  464. bool code_point_has_@enum_snake@(u32 code_point, @enum_title@ @enum_snake@)
  465. {
  466. auto stage1_index = code_point >> @CODE_POINT_TABLES_LSB_COUNT@;
  467. auto stage2_index = @collection_name@_stage1[stage1_index] + (code_point & @CODE_POINT_TABLES_LSB_MASK@);
  468. auto unique_properties_index = @collection_name@_stage2[stage2_index];
  469. auto const& property_set = @collection_name@_unique_properties[unique_properties_index];
  470. return property_set[to_underlying(@enum_snake@)];
  471. }
  472. )~~~");
  473. return {};
  474. };
  475. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& prop_list, Vector<Alias> const& aliases) -> ErrorOr<void> {
  476. HashValueMap<StringView> hashes;
  477. TRY(hashes.try_ensure_capacity(prop_list.size() + aliases.size()));
  478. ValueFromStringOptions options {};
  479. for (auto const& prop : prop_list) {
  480. if constexpr (IsSame<RemoveCVReference<decltype(prop)>, ByteString>) {
  481. hashes.set(CaseInsensitiveASCIIStringViewTraits::hash(prop), prop);
  482. options.sensitivity = CaseSensitivity::CaseInsensitive;
  483. } else {
  484. hashes.set(prop.key.hash(), prop.key);
  485. }
  486. }
  487. for (auto const& alias : aliases)
  488. hashes.set(alias.alias.hash(), alias.alias);
  489. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes), options);
  490. return {};
  491. };
  492. TRY(append_prop_search("GeneralCategory"sv, "general_category"sv, "s_general_categories"sv));
  493. TRY(append_from_string("GeneralCategory"sv, "general_category"sv, unicode_data.general_categories, unicode_data.general_category_aliases));
  494. TRY(append_prop_search("Property"sv, "property"sv, "s_properties"sv));
  495. TRY(append_from_string("Property"sv, "property"sv, unicode_data.prop_list, unicode_data.prop_aliases));
  496. TRY(append_prop_search("Script"sv, "script"sv, "s_scripts"sv));
  497. TRY(append_prop_search("Script"sv, "script_extension"sv, "s_script_extensions"sv));
  498. TRY(append_from_string("Script"sv, "script"sv, unicode_data.script_list, unicode_data.script_aliases));
  499. TRY(append_from_string("BidirectionalClass"sv, "bidirectional_class"sv, unicode_data.bidirectional_classes, {}));
  500. generator.append(R"~~~(
  501. }
  502. )~~~");
  503. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  504. return {};
  505. }
  506. static Vector<u32> flatten_code_point_ranges(Vector<Unicode::CodePointRange> const& code_points)
  507. {
  508. Vector<u32> flattened;
  509. for (auto const& range : code_points) {
  510. flattened.grow_capacity(range.last - range.first);
  511. for (u32 code_point = range.first; code_point <= range.last; ++code_point)
  512. flattened.append(code_point);
  513. }
  514. return flattened;
  515. }
  516. static Vector<Unicode::CodePointRange> form_code_point_ranges(Vector<u32> code_points)
  517. {
  518. Vector<Unicode::CodePointRange> ranges;
  519. u32 range_start = code_points[0];
  520. u32 range_end = range_start;
  521. for (size_t i = 1; i < code_points.size(); ++i) {
  522. u32 code_point = code_points[i];
  523. if ((code_point - range_end) == 1) {
  524. range_end = code_point;
  525. } else {
  526. ranges.append({ range_start, range_end });
  527. range_start = code_point;
  528. range_end = code_point;
  529. }
  530. }
  531. ranges.append({ range_start, range_end });
  532. return ranges;
  533. }
  534. static void sort_and_merge_code_point_ranges(Vector<Unicode::CodePointRange>& code_points)
  535. {
  536. quick_sort(code_points, [](auto const& range1, auto const& range2) {
  537. return range1.first < range2.first;
  538. });
  539. for (size_t i = 0; i < code_points.size() - 1;) {
  540. if (code_points[i].last >= code_points[i + 1].first) {
  541. code_points[i].last = max(code_points[i].last, code_points[i + 1].last);
  542. code_points.remove(i + 1);
  543. } else {
  544. ++i;
  545. }
  546. }
  547. auto all_code_points = flatten_code_point_ranges(code_points);
  548. code_points = form_code_point_ranges(all_code_points);
  549. }
  550. static void populate_general_category_unions(PropList& general_categories)
  551. {
  552. // The Unicode standard defines General Category values which are not in any UCD file. These
  553. // values are simply unions of other values.
  554. // https://www.unicode.org/reports/tr44/#GC_Values_Table
  555. auto populate_union = [&](auto alias, auto categories) {
  556. auto& code_points = general_categories.ensure(alias);
  557. for (auto const& category : categories)
  558. code_points.extend(general_categories.find(category)->value);
  559. sort_and_merge_code_point_ranges(code_points);
  560. };
  561. populate_union("LC"sv, Array { "Ll"sv, "Lu"sv, "Lt"sv });
  562. populate_union("L"sv, Array { "Lu"sv, "Ll"sv, "Lt"sv, "Lm"sv, "Lo"sv });
  563. populate_union("M"sv, Array { "Mn"sv, "Mc"sv, "Me"sv });
  564. populate_union("N"sv, Array { "Nd"sv, "Nl"sv, "No"sv });
  565. populate_union("P"sv, Array { "Pc"sv, "Pd"sv, "Ps"sv, "Pe"sv, "Pi"sv, "Pf"sv, "Po"sv });
  566. populate_union("S"sv, Array { "Sm"sv, "Sc"sv, "Sk"sv, "So"sv });
  567. populate_union("Z"sv, Array { "Zs"sv, "Zl"sv, "Zp"sv });
  568. populate_union("C"sv, Array { "Cc"sv, "Cf"sv, "Cs"sv, "Co"sv, "Cn"sv });
  569. }
  570. static ErrorOr<void> normalize_script_extensions(PropList& script_extensions, PropList const& script_list, Vector<Alias> const& script_aliases)
  571. {
  572. // The ScriptExtensions UCD file lays out its code point ranges rather uniquely compared to
  573. // other files. The Script listed on each line may either be a full Script string or an aliased
  574. // abbreviation. Further, the extensions may or may not include the base Script list. Normalize
  575. // the extensions here to be keyed by the full Script name and always include the base list.
  576. auto extensions = move(script_extensions);
  577. script_extensions = TRY(script_list.clone());
  578. for (auto const& extension : extensions) {
  579. auto it = find_if(script_aliases.begin(), script_aliases.end(), [&](auto const& alias) { return extension.key == alias.alias; });
  580. auto const& key = (it == script_aliases.end()) ? extension.key : it->name;
  581. auto& code_points = script_extensions.find(key)->value;
  582. code_points.extend(extension.value);
  583. sort_and_merge_code_point_ranges(code_points);
  584. }
  585. // Lastly, the Common and Inherited script extensions are special. They must not contain any
  586. // code points which appear in other script extensions. The ScriptExtensions UCD file does not
  587. // list these extensions, therefore this peculiarity must be handled programmatically.
  588. // https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values
  589. auto code_point_has_other_extension = [&](StringView key, u32 code_point) {
  590. for (auto const& extension : extensions) {
  591. if (extension.key == key)
  592. continue;
  593. if (any_of(extension.value, [&](auto const& r) { return (r.first <= code_point) && (code_point <= r.last); }))
  594. return true;
  595. }
  596. return false;
  597. };
  598. auto get_code_points_without_other_extensions = [&](StringView key) {
  599. auto code_points = flatten_code_point_ranges(script_list.find(key)->value);
  600. code_points.remove_all_matching([&](u32 c) { return code_point_has_other_extension(key, c); });
  601. return code_points;
  602. };
  603. auto common_code_points = get_code_points_without_other_extensions("Common"sv);
  604. script_extensions.set("Common"sv, form_code_point_ranges(common_code_points));
  605. auto inherited_code_points = get_code_points_without_other_extensions("Inherited"sv);
  606. script_extensions.set("Inherited"sv, form_code_point_ranges(inherited_code_points));
  607. return {};
  608. }
  609. struct PropertyMetadata {
  610. static ErrorOr<PropertyMetadata> create(PropList& property_list)
  611. {
  612. PropertyMetadata data;
  613. TRY(data.property_values.try_ensure_capacity(property_list.size()));
  614. TRY(data.property_set.try_ensure_capacity(property_list.size()));
  615. auto property_names = property_list.keys();
  616. quick_sort(property_names);
  617. for (auto& property_name : property_names) {
  618. auto& code_point_ranges = property_list.get(property_name).value();
  619. data.property_values.unchecked_append(move(code_point_ranges));
  620. }
  621. return data;
  622. }
  623. Vector<typename PropList::ValueType> property_values;
  624. PropertyTable property_set;
  625. Vector<size_t> current_block;
  626. HashMap<decltype(current_block), size_t> unique_blocks;
  627. };
  628. // The goal here is to produce a set of tables that represent a category of code point properties for every code point.
  629. // The most naive method would be to generate a single table per category, each with one entry per code point. Each of
  630. // those tables would have a size of 0x10ffff though, which is a non-starter. Instead, we create a set of 2-stage lookup
  631. // tables per category.
  632. //
  633. // To do so, it's important to note that Unicode tends to organize code points with similar properties together. This
  634. // leads to long series of code points with identical properties. Therefore, if we divide the 0x10ffff code points into
  635. // fixed-size blocks, many of those blocks will also be identical.
  636. //
  637. // So we iterate over every code point, classifying each one for the category of interest. We represent a classification
  638. // as a list of booleans. We store the classification in the CodePointTables::unique_properties list for this category.
  639. // As the name implies, this list is de-duplicated; we store the index into this list in a separate list, which we call
  640. // a "block".
  641. //
  642. // As we iterate, we "pause" every BLOCK_SIZE code points to examine the block. If the block is unique so far, we extend
  643. // CodePointTables::stage2 with the entries of that block (so CodePointTables::stage2 is also a list of indices into
  644. // CodePointTables::unique_properties). We then append the index of the start of that block in CodePointTables::stage2
  645. // to CodePointTables::stage1.
  646. //
  647. // The value of BLOCK_SIZE is determined by CodePointTables::MSB_COUNT and CodePointTables::LSB_COUNT. We need 24 bits
  648. // to describe all code points; the blocks we create are based on splitting these bits into 2 segments. We currently use
  649. // a 16:8 bit split. So when perform a runtime lookup of a code point in the 2-stage tables, we:
  650. //
  651. // 1. Use most-significant 16 bits of the code point as the index into CodePointTables::stage1. That value is the
  652. // index into CodePointTables::stage2 of the start of the block that contains properties for this code point.
  653. //
  654. // 2. Add the least-significant 8 bits of the code point to that value, to use as the index into
  655. // CodePointTables::stage2. As described above, that value is the index into CodePointTables::unique_properties,
  656. // which contains the classification for this code point.
  657. //
  658. // Using the code point GeneralCategory as an example, we end up with a CodePointTables::stage1 with a size of ~4000,
  659. // a CodePointTables::stage2 with a size of ~40,000, and a CodePointTables::unique_properties with a size of ~30. So
  660. // this process reduces over 1 million entries (0x10ffff) to ~44,030.
  661. //
  662. // For much more in-depth reading, see: https://icu.unicode.org/design/struct/utrie
  663. static constexpr auto MAX_CODE_POINT = 0x10ffffu;
  664. template<typename T>
  665. static ErrorOr<void> update_tables(u32 code_point, CodePointTables<T>& tables, auto& metadata, auto const& values)
  666. {
  667. static constexpr auto BLOCK_SIZE = CODE_POINT_TABLES_LSB_MASK + 1;
  668. size_t unique_properties_index = 0;
  669. if (auto block_index = tables.unique_properties.find_first_index(values); block_index.has_value()) {
  670. unique_properties_index = *block_index;
  671. } else {
  672. unique_properties_index = tables.unique_properties.size();
  673. TRY(tables.unique_properties.try_append(values));
  674. }
  675. TRY(metadata.current_block.try_append(unique_properties_index));
  676. if (metadata.current_block.size() == BLOCK_SIZE || code_point == MAX_CODE_POINT) {
  677. size_t stage2_index = 0;
  678. if (auto block_index = metadata.unique_blocks.get(metadata.current_block); block_index.has_value()) {
  679. stage2_index = *block_index;
  680. } else {
  681. stage2_index = tables.stage2.size();
  682. TRY(tables.stage2.try_extend(metadata.current_block));
  683. TRY(metadata.unique_blocks.try_set(metadata.current_block, stage2_index));
  684. }
  685. TRY(tables.stage1.try_append(stage2_index));
  686. metadata.current_block.clear_with_capacity();
  687. }
  688. return {};
  689. }
  690. static ErrorOr<void> create_code_point_tables(UnicodeData& unicode_data)
  691. {
  692. auto update_property_tables = [&]<typename T>(u32 code_point, CodePointTables<T>& tables, PropertyMetadata& metadata) -> ErrorOr<void> {
  693. static Unicode::CodePointRangeComparator comparator {};
  694. for (auto& property_values : metadata.property_values) {
  695. size_t ranges_to_remove = 0;
  696. auto has_property = false;
  697. for (auto const& range : property_values) {
  698. if (auto comparison = comparator(code_point, range); comparison <= 0) {
  699. has_property = comparison == 0;
  700. break;
  701. }
  702. ++ranges_to_remove;
  703. }
  704. metadata.property_set.unchecked_append(has_property);
  705. property_values.remove(0, ranges_to_remove);
  706. }
  707. TRY(update_tables(code_point, tables, metadata, metadata.property_set));
  708. metadata.property_set.clear_with_capacity();
  709. return {};
  710. };
  711. auto general_category_metadata = TRY(PropertyMetadata::create(unicode_data.general_categories));
  712. auto property_metadata = TRY(PropertyMetadata::create(unicode_data.prop_list));
  713. auto script_metadata = TRY(PropertyMetadata::create(unicode_data.script_list));
  714. auto script_extension_metadata = TRY(PropertyMetadata::create(unicode_data.script_extensions));
  715. for (u32 code_point = 0; code_point <= MAX_CODE_POINT; ++code_point) {
  716. TRY(update_property_tables(code_point, unicode_data.general_category_tables, general_category_metadata));
  717. TRY(update_property_tables(code_point, unicode_data.property_tables, property_metadata));
  718. TRY(update_property_tables(code_point, unicode_data.script_tables, script_metadata));
  719. TRY(update_property_tables(code_point, unicode_data.script_extension_tables, script_extension_metadata));
  720. }
  721. return {};
  722. }
  723. ErrorOr<int> serenity_main(Main::Arguments arguments)
  724. {
  725. StringView generated_header_path;
  726. StringView generated_implementation_path;
  727. StringView unicode_data_path;
  728. StringView derived_general_category_path;
  729. StringView prop_list_path;
  730. StringView derived_core_prop_path;
  731. StringView derived_binary_prop_path;
  732. StringView prop_alias_path;
  733. StringView prop_value_alias_path;
  734. StringView scripts_path;
  735. StringView script_extensions_path;
  736. StringView emoji_data_path;
  737. StringView normalization_path;
  738. Core::ArgsParser args_parser;
  739. args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path");
  740. args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  741. args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path");
  742. args_parser.add_option(derived_general_category_path, "Path to DerivedGeneralCategory.txt file", "derived-general-category-path", 'g', "derived-general-category-path");
  743. args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path");
  744. args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path");
  745. args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path");
  746. args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path");
  747. args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path");
  748. args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path");
  749. args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path");
  750. args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path");
  751. args_parser.add_option(normalization_path, "Path to DerivedNormalizationProps.txt file", "normalization-path", 'n', "normalization-path");
  752. args_parser.parse(arguments);
  753. auto generated_header_file = TRY(open_file(generated_header_path, Core::File::OpenMode::Write));
  754. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::File::OpenMode::Write));
  755. auto unicode_data_file = TRY(open_file(unicode_data_path, Core::File::OpenMode::Read));
  756. auto derived_general_category_file = TRY(open_file(derived_general_category_path, Core::File::OpenMode::Read));
  757. auto prop_list_file = TRY(open_file(prop_list_path, Core::File::OpenMode::Read));
  758. auto derived_core_prop_file = TRY(open_file(derived_core_prop_path, Core::File::OpenMode::Read));
  759. auto derived_binary_prop_file = TRY(open_file(derived_binary_prop_path, Core::File::OpenMode::Read));
  760. auto prop_alias_file = TRY(open_file(prop_alias_path, Core::File::OpenMode::Read));
  761. auto prop_value_alias_file = TRY(open_file(prop_value_alias_path, Core::File::OpenMode::Read));
  762. auto scripts_file = TRY(open_file(scripts_path, Core::File::OpenMode::Read));
  763. auto script_extensions_file = TRY(open_file(script_extensions_path, Core::File::OpenMode::Read));
  764. auto emoji_data_file = TRY(open_file(emoji_data_path, Core::File::OpenMode::Read));
  765. auto normalization_file = TRY(open_file(normalization_path, Core::File::OpenMode::Read));
  766. UnicodeData unicode_data {};
  767. TRY(parse_prop_list(*derived_general_category_file, unicode_data.general_categories));
  768. TRY(parse_prop_list(*prop_list_file, unicode_data.prop_list));
  769. TRY(parse_prop_list(*derived_core_prop_file, unicode_data.prop_list));
  770. TRY(parse_prop_list(*derived_binary_prop_file, unicode_data.prop_list));
  771. TRY(parse_prop_list(*emoji_data_file, unicode_data.prop_list));
  772. TRY(parse_normalization_props(*normalization_file, unicode_data));
  773. TRY(parse_alias_list(*prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases));
  774. TRY(parse_prop_list(*scripts_file, unicode_data.script_list));
  775. TRY(parse_prop_list(*script_extensions_file, unicode_data.script_extensions, true));
  776. populate_general_category_unions(unicode_data.general_categories);
  777. TRY(parse_unicode_data(*unicode_data_file, unicode_data));
  778. TRY(parse_value_alias_list(*prop_value_alias_file, "gc"sv, unicode_data.general_categories.keys(), unicode_data.general_category_aliases));
  779. TRY(parse_value_alias_list(*prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), unicode_data.script_aliases, false));
  780. TRY(normalize_script_extensions(unicode_data.script_extensions, unicode_data.script_list, unicode_data.script_aliases));
  781. TRY(create_code_point_tables(unicode_data));
  782. TRY(generate_unicode_data_header(*generated_header_file, unicode_data));
  783. TRY(generate_unicode_data_implementation(*generated_implementation_file, unicode_data));
  784. return 0;
  785. }