GenerateUnicodeData.cpp 33 KB

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