GenerateLocaleData.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*
  2. * Copyright (c) 2021-2022, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "../LibUnicode/GeneratorUtil.h" // FIXME: Move this somewhere common.
  7. #include <AK/AllOf.h>
  8. #include <AK/ByteString.h>
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Error.h>
  11. #include <AK/Format.h>
  12. #include <AK/HashMap.h>
  13. #include <AK/JsonObject.h>
  14. #include <AK/JsonParser.h>
  15. #include <AK/JsonValue.h>
  16. #include <AK/LexicalPath.h>
  17. #include <AK/QuickSort.h>
  18. #include <AK/SourceGenerator.h>
  19. #include <AK/StringBuilder.h>
  20. #include <LibCore/ArgsParser.h>
  21. #include <LibCore/Directory.h>
  22. #include <LibFileSystem/FileSystem.h>
  23. static ByteString format_identifier(StringView owner, ByteString identifier)
  24. {
  25. identifier = identifier.replace("-"sv, "_"sv, ReplaceMode::All);
  26. if (all_of(identifier, is_ascii_digit))
  27. return ByteString::formatted("{}_{}", owner[0], identifier);
  28. if (is_ascii_lower_alpha(identifier[0]))
  29. return ByteString::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  30. return identifier;
  31. }
  32. using KeywordList = Vector<size_t>;
  33. struct LocaleData {
  34. size_t calendar_keywords { 0 };
  35. size_t collation_case_keywords { 0 };
  36. size_t collation_numeric_keywords { 0 };
  37. size_t number_system_keywords { 0 };
  38. size_t text_layout { 0 };
  39. };
  40. struct CLDR {
  41. UniqueStringStorage unique_strings;
  42. UniqueStorage<KeywordList> unique_keyword_lists;
  43. HashMap<ByteString, LocaleData> locales;
  44. Vector<Alias> locale_aliases;
  45. HashMap<ByteString, Vector<ByteString>> keywords;
  46. HashMap<ByteString, Vector<Alias>> keyword_aliases;
  47. HashMap<ByteString, ByteString> keyword_names;
  48. };
  49. // Some parsing is expected to fail. For example, the CLDR contains language mappings
  50. // with locales such as "en-GB-oed" that are canonically invalid locale IDs.
  51. #define TRY_OR_DISCARD(expression) \
  52. ({ \
  53. auto&& _temporary_result = (expression); \
  54. if (_temporary_result.is_error()) \
  55. return; \
  56. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  57. "Do not return a reference from a fallible expression"); \
  58. _temporary_result.release_value(); \
  59. })
  60. // NOTE: We return a pointer only because ErrorOr cannot store references. You may safely assume the pointer is non-null.
  61. ErrorOr<JsonValue const*> read_json_file_with_cache(ByteString const& path)
  62. {
  63. static HashMap<ByteString, JsonValue> parsed_json_cache;
  64. if (auto parsed_json = parsed_json_cache.get(path); parsed_json.has_value())
  65. return &parsed_json.value();
  66. auto parsed_json = TRY(read_json_file(path));
  67. TRY(parsed_json_cache.try_set(path, move(parsed_json)));
  68. return &parsed_json_cache.get(path).value();
  69. }
  70. static ErrorOr<void> parse_unicode_extension_keywords(ByteString bcp47_path, CLDR& cldr)
  71. {
  72. constexpr auto desired_keywords = Array { "ca"sv, "co"sv, "hc"sv, "kf"sv, "kn"sv, "nu"sv };
  73. auto keywords = TRY(read_json_file(bcp47_path));
  74. auto const& keyword_object = keywords.as_object().get_object("keyword"sv).value();
  75. auto unicode_object = keyword_object.get_object("u"sv);
  76. if (!unicode_object.has_value())
  77. return {};
  78. unicode_object->for_each_member([&](auto const& key, auto const& value) {
  79. if (!desired_keywords.span().contains_slow(key))
  80. return;
  81. auto const& name = value.as_object().get_byte_string("_alias"sv).value();
  82. cldr.keyword_names.set(key, name);
  83. auto& keywords = cldr.keywords.ensure(key);
  84. // FIXME: ECMA-402 requires the list of supported collation types to include "default", but
  85. // that type does not appear in collation.json.
  86. if (key == "co" && !keywords.contains_slow("default"sv))
  87. keywords.append("default"sv);
  88. value.as_object().for_each_member([&](auto const& keyword, auto const& properties) {
  89. if (!properties.is_object())
  90. return;
  91. // Filter out values not permitted by ECMA-402.
  92. // https://tc39.es/ecma402/#sec-intl-collator-internal-slots
  93. if (key == "co"sv && keyword.is_one_of("search"sv, "standard"sv))
  94. return;
  95. // https://tc39.es/ecma402/#sec-intl.numberformat-internal-slots
  96. if (key == "nu"sv && keyword.is_one_of("finance"sv, "native"sv, "traditio"sv))
  97. return;
  98. if (auto const& preferred = properties.as_object().get_byte_string("_preferred"sv); preferred.has_value()) {
  99. cldr.keyword_aliases.ensure(key).append({ preferred.value(), keyword });
  100. return;
  101. }
  102. if (auto const& alias = properties.as_object().get_byte_string("_alias"sv); alias.has_value())
  103. cldr.keyword_aliases.ensure(key).append({ keyword, alias.value() });
  104. keywords.append(keyword);
  105. });
  106. });
  107. return {};
  108. }
  109. static Optional<ByteString> find_keyword_alias(StringView key, StringView calendar, CLDR& cldr)
  110. {
  111. auto it = cldr.keyword_aliases.find(key);
  112. if (it == cldr.keyword_aliases.end())
  113. return {};
  114. auto alias = it->value.find_if([&](auto const& alias) { return calendar == alias.alias; });
  115. if (alias == it->value.end())
  116. return {};
  117. return alias->name;
  118. }
  119. static ErrorOr<void> parse_number_system_keywords(ByteString locale_numbers_path, CLDR& cldr, LocaleData& locale)
  120. {
  121. LexicalPath numbers_path(move(locale_numbers_path));
  122. numbers_path = numbers_path.append("numbers.json"sv);
  123. auto numbers = TRY(read_json_file(numbers_path.string()));
  124. auto const& main_object = numbers.as_object().get_object("main"sv).value();
  125. auto const& locale_object = main_object.get_object(numbers_path.parent().basename()).value();
  126. auto const& locale_numbers_object = locale_object.get_object("numbers"sv).value();
  127. auto const& default_numbering_system_object = locale_numbers_object.get_byte_string("defaultNumberingSystem"sv).value();
  128. auto const& other_numbering_systems_object = locale_numbers_object.get_object("otherNumberingSystems"sv).value();
  129. KeywordList keywords {};
  130. auto append_numbering_system = [&](ByteString system_name) {
  131. if (auto system_alias = find_keyword_alias("nu"sv, system_name, cldr); system_alias.has_value())
  132. system_name = system_alias.release_value();
  133. auto index = cldr.unique_strings.ensure(move(system_name));
  134. if (!keywords.contains_slow(index))
  135. keywords.append(move(index));
  136. };
  137. append_numbering_system(default_numbering_system_object);
  138. other_numbering_systems_object.for_each_member([&](auto const&, JsonValue const& value) {
  139. append_numbering_system(value.as_string());
  140. });
  141. locale_numbers_object.for_each_member([&](auto const& key, JsonValue const& value) {
  142. if (!key.starts_with("defaultNumberingSystem-alt-"sv))
  143. return;
  144. append_numbering_system(value.as_string());
  145. });
  146. locale.number_system_keywords = cldr.unique_keyword_lists.ensure(move(keywords));
  147. return {};
  148. }
  149. static ErrorOr<void> parse_calendar_keywords(ByteString locale_dates_path, CLDR& cldr, LocaleData& locale)
  150. {
  151. KeywordList keywords {};
  152. TRY(Core::Directory::for_each_entry(locale_dates_path, Core::DirIterator::SkipParentAndBaseDir, [&](auto& entry, auto& directory) -> ErrorOr<IterationDecision> {
  153. if (!entry.name.starts_with("ca-"sv))
  154. return IterationDecision::Continue;
  155. // The generic calendar is not a supported Unicode calendar key, so skip it:
  156. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#unicode_calendar_keys
  157. if (entry.name == "ca-generic.json"sv)
  158. return IterationDecision::Continue;
  159. auto locale_calendars_path = LexicalPath::join(directory.path().string(), entry.name).string();
  160. LexicalPath calendars_path(move(locale_calendars_path));
  161. auto calendars = TRY(read_json_file(calendars_path.string()));
  162. auto const& main_object = calendars.as_object().get_object("main"sv).value();
  163. auto const& locale_object = main_object.get_object(calendars_path.parent().basename()).value();
  164. auto const& dates_object = locale_object.get_object("dates"sv).value();
  165. auto const& calendars_object = dates_object.get_object("calendars"sv).value();
  166. calendars_object.for_each_member([&](auto calendar_name, JsonValue const&) {
  167. if (auto calendar_alias = find_keyword_alias("ca"sv, calendar_name, cldr); calendar_alias.has_value())
  168. calendar_name = calendar_alias.release_value();
  169. keywords.append(cldr.unique_strings.ensure(calendar_name));
  170. });
  171. return IterationDecision::Continue;
  172. }));
  173. locale.calendar_keywords = cldr.unique_keyword_lists.ensure(move(keywords));
  174. return {};
  175. }
  176. static void fill_in_collation_keywords(CLDR& cldr, LocaleData& locale)
  177. {
  178. // FIXME: If collation data becomes available in the CLDR, parse per-locale ordering from there.
  179. auto create_list_with_default_first = [&](auto key, auto default_value) {
  180. auto& values = cldr.keywords.find(key)->value;
  181. quick_sort(values, [&](auto const& lhs, auto const& rhs) {
  182. if (lhs == default_value)
  183. return true;
  184. if (rhs == default_value)
  185. return false;
  186. return lhs < rhs;
  187. });
  188. KeywordList keywords;
  189. keywords.ensure_capacity(values.size());
  190. for (auto const& value : values)
  191. keywords.append(cldr.unique_strings.ensure(value));
  192. return cldr.unique_keyword_lists.ensure(move(keywords));
  193. };
  194. static auto kf_index = create_list_with_default_first("kf"sv, "upper"sv);
  195. static auto kn_index = create_list_with_default_first("kn"sv, "true"sv);
  196. locale.collation_case_keywords = kf_index;
  197. locale.collation_numeric_keywords = kn_index;
  198. }
  199. static ErrorOr<void> parse_default_content_locales(ByteString core_path, CLDR& cldr)
  200. {
  201. LexicalPath default_content_path(move(core_path));
  202. default_content_path = default_content_path.append("defaultContent.json"sv);
  203. auto default_content = TRY(read_json_file(default_content_path.string()));
  204. auto const& default_content_array = default_content.as_object().get_array("defaultContent"sv).value();
  205. default_content_array.for_each([&](JsonValue const& value) {
  206. auto locale = value.as_string();
  207. StringView default_locale = locale;
  208. while (true) {
  209. if (cldr.locales.contains(default_locale))
  210. break;
  211. auto pos = default_locale.find_last('-');
  212. if (!pos.has_value())
  213. return;
  214. default_locale = default_locale.substring_view(0, *pos);
  215. }
  216. if (default_locale != locale)
  217. cldr.locale_aliases.append({ default_locale, move(locale) });
  218. });
  219. return {};
  220. }
  221. static ErrorOr<void> define_aliases_without_scripts(CLDR& cldr)
  222. {
  223. // From ECMA-402: https://tc39.es/ecma402/#sec-internal-slots
  224. //
  225. // For locales that include a script subtag in addition to language and region, the
  226. // corresponding locale without a script subtag must also be supported.
  227. //
  228. // So we define aliases for locales that contain all three subtags, but we must also take
  229. // care to handle when the locale itself or the locale without a script subtag are an alias
  230. // by way of default-content locales.
  231. auto find_alias = [&](auto const& locale) {
  232. return cldr.locale_aliases.find_if([&](auto const& alias) { return locale == alias.alias; });
  233. };
  234. auto append_alias_without_script = [&](auto const& locale) -> ErrorOr<void> {
  235. auto parsed_locale = TRY(CanonicalLanguageID::parse(cldr.unique_strings, locale));
  236. if ((parsed_locale.language == 0) || (parsed_locale.script == 0) || (parsed_locale.region == 0))
  237. return {};
  238. auto locale_without_script = ByteString::formatted("{}-{}",
  239. cldr.unique_strings.get(parsed_locale.language),
  240. cldr.unique_strings.get(parsed_locale.region));
  241. if (cldr.locales.contains(locale_without_script))
  242. return {};
  243. if (find_alias(locale_without_script) != cldr.locale_aliases.end())
  244. return {};
  245. if (auto it = find_alias(locale); it != cldr.locale_aliases.end())
  246. cldr.locale_aliases.append({ it->name, locale_without_script });
  247. else
  248. cldr.locale_aliases.append({ locale, locale_without_script });
  249. return {};
  250. };
  251. for (auto const& locale : cldr.locales)
  252. TRY(append_alias_without_script(locale.key));
  253. for (auto const& locale : cldr.locale_aliases)
  254. TRY(append_alias_without_script(locale.alias));
  255. return {};
  256. }
  257. static ErrorOr<void> parse_all_locales(ByteString bcp47_path, ByteString core_path, ByteString numbers_path, ByteString dates_path, CLDR& cldr)
  258. {
  259. LexicalPath core_supplemental_path(core_path);
  260. core_supplemental_path = core_supplemental_path.append("supplemental"sv);
  261. VERIFY(FileSystem::is_directory(core_supplemental_path.string()));
  262. auto remove_variants_from_path = [&](ByteString path) -> ErrorOr<ByteString> {
  263. auto parsed_locale = TRY(CanonicalLanguageID::parse(cldr.unique_strings, LexicalPath::basename(path)));
  264. StringBuilder builder;
  265. builder.append(cldr.unique_strings.get(parsed_locale.language));
  266. if (auto script = cldr.unique_strings.get(parsed_locale.script); !script.is_empty())
  267. builder.appendff("-{}", script);
  268. if (auto region = cldr.unique_strings.get(parsed_locale.region); !region.is_empty())
  269. builder.appendff("-{}", region);
  270. return builder.to_byte_string();
  271. };
  272. TRY(Core::Directory::for_each_entry(TRY(String::formatted("{}/bcp47", bcp47_path)), Core::DirIterator::SkipParentAndBaseDir, [&](auto& entry, auto& directory) -> ErrorOr<IterationDecision> {
  273. auto bcp47_path = LexicalPath::join(directory.path().string(), entry.name).string();
  274. TRY(parse_unicode_extension_keywords(move(bcp47_path), cldr));
  275. return IterationDecision::Continue;
  276. }));
  277. TRY(Core::Directory::for_each_entry(TRY(String::formatted("{}/main", numbers_path)), Core::DirIterator::SkipParentAndBaseDir, [&](auto& entry, auto& directory) -> ErrorOr<IterationDecision> {
  278. auto numbers_path = LexicalPath::join(directory.path().string(), entry.name).string();
  279. auto language = TRY(remove_variants_from_path(numbers_path));
  280. auto& locale = cldr.locales.ensure(language);
  281. TRY(parse_number_system_keywords(numbers_path, cldr, locale));
  282. fill_in_collation_keywords(cldr, locale);
  283. return IterationDecision::Continue;
  284. }));
  285. TRY(Core::Directory::for_each_entry(TRY(String::formatted("{}/main", dates_path)), Core::DirIterator::SkipParentAndBaseDir, [&](auto& entry, auto& directory) -> ErrorOr<IterationDecision> {
  286. auto dates_path = LexicalPath::join(directory.path().string(), entry.name).string();
  287. auto language = TRY(remove_variants_from_path(dates_path));
  288. auto& locale = cldr.locales.ensure(language);
  289. TRY(parse_calendar_keywords(dates_path, cldr, locale));
  290. return IterationDecision::Continue;
  291. }));
  292. TRY(parse_default_content_locales(move(core_path), cldr));
  293. TRY(define_aliases_without_scripts(cldr));
  294. return {};
  295. }
  296. static ErrorOr<void> generate_unicode_locale_header(Core::InputBufferedFile& file, CLDR& cldr)
  297. {
  298. StringBuilder builder;
  299. SourceGenerator generator { builder };
  300. generator.append(R"~~~(
  301. #pragma once
  302. #include <AK/Types.h>
  303. namespace Locale {
  304. )~~~");
  305. auto locales = cldr.locales.keys();
  306. auto keywords = cldr.keywords.keys();
  307. generate_enum(generator, format_identifier, "Locale"sv, "None"sv, locales, cldr.locale_aliases);
  308. generate_enum(generator, format_identifier, "Key"sv, {}, keywords);
  309. for (auto& keyword : cldr.keywords) {
  310. auto const& keyword_name = cldr.keyword_names.find(keyword.key)->value;
  311. auto enum_name = ByteString::formatted("Keyword{}", format_identifier({}, keyword_name));
  312. if (auto aliases = cldr.keyword_aliases.find(keyword.key); aliases != cldr.keyword_aliases.end())
  313. generate_enum(generator, format_identifier, enum_name, {}, keyword.value, aliases->value);
  314. else
  315. generate_enum(generator, format_identifier, enum_name, {}, keyword.value);
  316. }
  317. generator.append(R"~~~(
  318. }
  319. )~~~");
  320. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  321. return {};
  322. }
  323. static ErrorOr<void> generate_unicode_locale_implementation(Core::InputBufferedFile& file, CLDR& cldr)
  324. {
  325. auto string_index_type = cldr.unique_strings.type_that_fits();
  326. StringBuilder builder;
  327. SourceGenerator generator { builder };
  328. generator.set("string_index_type"sv, string_index_type);
  329. generator.set("locales_size"sv, ByteString::number(cldr.locales.size()));
  330. generator.append(R"~~~(
  331. #include <AK/Array.h>
  332. #include <AK/BinarySearch.h>
  333. #include <AK/Optional.h>
  334. #include <AK/Span.h>
  335. #include <AK/String.h>
  336. #include <AK/StringView.h>
  337. #include <AK/Vector.h>
  338. #include <LibLocale/DateTimeFormat.h>
  339. #include <LibLocale/Locale.h>
  340. #include <LibLocale/LocaleData.h>
  341. #include <LibUnicode/CurrencyCode.h>
  342. namespace Locale {
  343. )~~~");
  344. cldr.unique_strings.generate(generator);
  345. generate_available_values(generator, "get_available_calendars"sv, cldr.keywords.find("ca"sv)->value, cldr.keyword_aliases.find("ca"sv)->value,
  346. [](auto calendar) {
  347. // FIXME: Remove this filter when we support all calendars.
  348. return calendar.is_one_of("gregory"sv, "iso8601"sv);
  349. });
  350. generate_available_values(generator, "get_available_collation_case_orderings"sv, cldr.keywords.find("kf"sv)->value, cldr.keyword_aliases.find("kf"sv)->value);
  351. generate_available_values(generator, "get_available_collation_numeric_orderings"sv, cldr.keywords.find("kn"sv)->value, cldr.keyword_aliases.find("kn"sv)->value);
  352. generate_available_values(generator, "get_available_collation_types"sv, cldr.keywords.find("co"sv)->value, cldr.keyword_aliases.find("co"sv)->value,
  353. [](auto collation) {
  354. // FIXME: Remove this filter when we support all collation types.
  355. return collation == "default"sv;
  356. });
  357. generate_available_values(generator, "get_available_hour_cycles"sv, cldr.keywords.find("hc"sv)->value);
  358. generate_available_values(generator, "get_available_number_systems"sv, cldr.keywords.find("nu"sv)->value);
  359. generator.append(R"~~~(
  360. ReadonlySpan<StringView> get_available_keyword_values(StringView key)
  361. {
  362. auto key_value = key_from_string(key);
  363. if (!key_value.has_value())
  364. return {};
  365. switch (*key_value) {
  366. case Key::Ca:
  367. return get_available_calendars();
  368. case Key::Co:
  369. return get_available_collation_types();
  370. case Key::Hc:
  371. return get_available_hour_cycles();
  372. case Key::Kf:
  373. return get_available_collation_case_orderings();
  374. case Key::Kn:
  375. return get_available_collation_numeric_orderings();
  376. case Key::Nu:
  377. return get_available_number_systems();
  378. }
  379. VERIFY_NOT_REACHED();
  380. }
  381. )~~~");
  382. cldr.unique_keyword_lists.generate(generator, string_index_type, "s_keyword_lists"sv);
  383. auto append_mapping = [&](auto const& keys, auto const& map, auto type, auto name, auto mapping_getter) {
  384. generator.set("type", type);
  385. generator.set("name", name);
  386. generator.set("size", ByteString::number(keys.size()));
  387. generator.append(R"~~~(
  388. static constexpr Array<@type@, @size@> @name@ { {)~~~");
  389. bool first = true;
  390. for (auto const& key : keys) {
  391. auto const& value = map.find(key)->value;
  392. auto mapping = mapping_getter(value);
  393. generator.append(first ? " "sv : ", "sv);
  394. generator.append(ByteString::number(mapping));
  395. first = false;
  396. }
  397. generator.append(" } };");
  398. };
  399. auto locales = cldr.locales.keys();
  400. quick_sort(locales);
  401. append_mapping(locales, cldr.locales, cldr.unique_keyword_lists.type_that_fits(), "s_calendar_keywords"sv, [&](auto const& locale) { return locale.calendar_keywords; });
  402. append_mapping(locales, cldr.locales, cldr.unique_keyword_lists.type_that_fits(), "s_collation_case_keywords"sv, [&](auto const& locale) { return locale.collation_case_keywords; });
  403. append_mapping(locales, cldr.locales, cldr.unique_keyword_lists.type_that_fits(), "s_collation_numeric_keywords"sv, [&](auto const& locale) { return locale.collation_numeric_keywords; });
  404. append_mapping(locales, cldr.locales, cldr.unique_keyword_lists.type_that_fits(), "s_number_system_keywords"sv, [&](auto const& locale) { return locale.number_system_keywords; });
  405. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) -> ErrorOr<void> {
  406. HashValueMap<ByteString> hashes;
  407. TRY(hashes.try_ensure_capacity(values.size()));
  408. for (auto const& value : values)
  409. hashes.set(value.hash(), format_identifier(enum_title, value));
  410. for (auto const& alias : aliases)
  411. hashes.set(alias.alias.hash(), format_identifier(enum_title, alias.alias));
  412. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  413. return {};
  414. };
  415. TRY(append_from_string("Locale"sv, "locale"sv, cldr.locales.keys(), cldr.locale_aliases));
  416. TRY(append_from_string("Key"sv, "key"sv, cldr.keywords.keys()));
  417. for (auto const& keyword : cldr.keywords) {
  418. auto const& keyword_name = cldr.keyword_names.find(keyword.key)->value;
  419. auto enum_name = ByteString::formatted("Keyword{}", format_identifier({}, keyword_name));
  420. auto enum_snake = ByteString::formatted("keyword_{}", keyword.key);
  421. if (auto aliases = cldr.keyword_aliases.find(keyword.key); aliases != cldr.keyword_aliases.end())
  422. TRY(append_from_string(enum_name, enum_snake, keyword.value, aliases->value));
  423. else
  424. TRY(append_from_string(enum_name, enum_snake, keyword.value));
  425. }
  426. generator.append(R"~~~(
  427. static ReadonlySpan<@string_index_type@> find_keyword_indices(StringView locale, StringView key)
  428. {
  429. auto locale_value = locale_from_string(locale);
  430. if (!locale_value.has_value())
  431. return {};
  432. auto key_value = key_from_string(key);
  433. if (!key_value.has_value())
  434. return {};
  435. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  436. size_t keywords_index = 0;
  437. switch (*key_value) {
  438. case Key::Ca:
  439. keywords_index = s_calendar_keywords.at(locale_index);
  440. break;
  441. case Key::Kf:
  442. keywords_index = s_collation_case_keywords.at(locale_index);
  443. break;
  444. case Key::Kn:
  445. keywords_index = s_collation_numeric_keywords.at(locale_index);
  446. break;
  447. case Key::Nu:
  448. keywords_index = s_number_system_keywords.at(locale_index);
  449. break;
  450. default:
  451. VERIFY_NOT_REACHED();
  452. }
  453. return s_keyword_lists.at(keywords_index);
  454. }
  455. Optional<StringView> get_preferred_keyword_value_for_locale(StringView locale, StringView key)
  456. {
  457. // Hour cycle keywords are region-based rather than locale-based, so they need to be handled specially.
  458. // FIXME: Calendar keywords are also region-based, and will need to be handled here when we support non-Gregorian calendars:
  459. // https://github.com/unicode-org/cldr-json/blob/main/cldr-json/cldr-core/supplemental/calendarPreferenceData.json
  460. if (key == "hc"sv) {
  461. auto hour_cycles = get_locale_hour_cycles(locale);
  462. if (hour_cycles.is_empty())
  463. return OptionalNone {};
  464. return Optional<StringView> { hour_cycle_to_string(hour_cycles[0]) };
  465. }
  466. // FIXME: Generate locale-preferred collation data when available in the CLDR.
  467. if (key == "co"sv) {
  468. auto collations = get_available_collation_types();
  469. if (collations.is_empty())
  470. return OptionalNone {};
  471. return Optional<StringView> { collations[0] };
  472. }
  473. auto keyword_indices = find_keyword_indices(locale, key);
  474. if (keyword_indices.is_empty())
  475. return OptionalNone {};
  476. return Optional<StringView> { decode_string(keyword_indices[0]) };
  477. }
  478. Vector<StringView> get_keywords_for_locale(StringView locale, StringView key)
  479. {
  480. // Hour cycle keywords are region-based rather than locale-based, so they need to be handled specially.
  481. // FIXME: Calendar keywords are also region-based, and will need to be handled here when we support non-Gregorian calendars:
  482. // https://github.com/unicode-org/cldr-json/blob/main/cldr-json/cldr-core/supplemental/calendarPreferenceData.json
  483. if (key == "hc"sv) {
  484. auto hour_cycles = get_locale_hour_cycles(locale);
  485. Vector<StringView> values;
  486. values.ensure_capacity(hour_cycles.size());
  487. for (auto hour_cycle : hour_cycles)
  488. values.unchecked_append(hour_cycle_to_string(hour_cycle));
  489. return values;
  490. }
  491. // FIXME: Generate locale-preferred collation data when available in the CLDR.
  492. if (key == "co"sv)
  493. return Vector<StringView> { get_available_collation_types() };
  494. auto keyword_indices = find_keyword_indices(locale, key);
  495. Vector<StringView> keywords;
  496. keywords.ensure_capacity(keyword_indices.size());
  497. for (auto keyword : keyword_indices)
  498. keywords.unchecked_append(decode_string(keyword));
  499. return keywords;
  500. }
  501. }
  502. )~~~");
  503. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  504. return {};
  505. }
  506. ErrorOr<int> serenity_main(Main::Arguments arguments)
  507. {
  508. StringView generated_header_path;
  509. StringView generated_implementation_path;
  510. StringView bcp47_path;
  511. StringView core_path;
  512. StringView numbers_path;
  513. StringView dates_path;
  514. Core::ArgsParser args_parser;
  515. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  516. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  517. args_parser.add_option(bcp47_path, "Path to cldr-bcp47 directory", "bcp47-path", 'b', "bcp47-path");
  518. args_parser.add_option(core_path, "Path to cldr-core directory", "core-path", 'r', "core-path");
  519. args_parser.add_option(numbers_path, "Path to cldr-numbers directory", "numbers-path", 'n', "numbers-path");
  520. args_parser.add_option(dates_path, "Path to cldr-dates directory", "dates-path", 'd', "dates-path");
  521. args_parser.parse(arguments);
  522. auto generated_header_file = TRY(open_file(generated_header_path, Core::File::OpenMode::Write));
  523. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::File::OpenMode::Write));
  524. CLDR cldr;
  525. TRY(parse_all_locales(bcp47_path, core_path, numbers_path, dates_path, cldr));
  526. TRY(generate_unicode_locale_header(*generated_header_file, cldr));
  527. TRY(generate_unicode_locale_implementation(*generated_implementation_file, cldr));
  528. return 0;
  529. }