GenerateLocaleData.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. struct LocaleData {
  33. };
  34. struct CLDR {
  35. UniqueStringStorage unique_strings;
  36. HashMap<ByteString, LocaleData> locales;
  37. Vector<Alias> locale_aliases;
  38. };
  39. // Some parsing is expected to fail. For example, the CLDR contains language mappings
  40. // with locales such as "en-GB-oed" that are canonically invalid locale IDs.
  41. #define TRY_OR_DISCARD(expression) \
  42. ({ \
  43. auto&& _temporary_result = (expression); \
  44. if (_temporary_result.is_error()) \
  45. return; \
  46. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  47. "Do not return a reference from a fallible expression"); \
  48. _temporary_result.release_value(); \
  49. })
  50. // NOTE: We return a pointer only because ErrorOr cannot store references. You may safely assume the pointer is non-null.
  51. ErrorOr<JsonValue const*> read_json_file_with_cache(ByteString const& path)
  52. {
  53. static HashMap<ByteString, JsonValue> parsed_json_cache;
  54. if (auto parsed_json = parsed_json_cache.get(path); parsed_json.has_value())
  55. return &parsed_json.value();
  56. auto parsed_json = TRY(read_json_file(path));
  57. TRY(parsed_json_cache.try_set(path, move(parsed_json)));
  58. return &parsed_json_cache.get(path).value();
  59. }
  60. static ErrorOr<void> parse_default_content_locales(ByteString core_path, CLDR& cldr)
  61. {
  62. LexicalPath default_content_path(move(core_path));
  63. default_content_path = default_content_path.append("defaultContent.json"sv);
  64. auto default_content = TRY(read_json_file(default_content_path.string()));
  65. auto const& default_content_array = default_content.as_object().get_array("defaultContent"sv).value();
  66. default_content_array.for_each([&](JsonValue const& value) {
  67. auto locale = value.as_string();
  68. StringView default_locale = locale;
  69. while (true) {
  70. if (cldr.locales.contains(default_locale))
  71. break;
  72. auto pos = default_locale.find_last('-');
  73. if (!pos.has_value())
  74. return;
  75. default_locale = default_locale.substring_view(0, *pos);
  76. }
  77. if (default_locale != locale)
  78. cldr.locale_aliases.append({ default_locale, move(locale) });
  79. });
  80. return {};
  81. }
  82. static ErrorOr<void> define_aliases_without_scripts(CLDR& cldr)
  83. {
  84. // From ECMA-402: https://tc39.es/ecma402/#sec-internal-slots
  85. //
  86. // For locales that include a script subtag in addition to language and region, the
  87. // corresponding locale without a script subtag must also be supported.
  88. //
  89. // So we define aliases for locales that contain all three subtags, but we must also take
  90. // care to handle when the locale itself or the locale without a script subtag are an alias
  91. // by way of default-content locales.
  92. auto find_alias = [&](auto const& locale) {
  93. return cldr.locale_aliases.find_if([&](auto const& alias) { return locale == alias.alias; });
  94. };
  95. auto append_alias_without_script = [&](auto const& locale) -> ErrorOr<void> {
  96. auto parsed_locale = TRY(CanonicalLanguageID::parse(cldr.unique_strings, locale));
  97. if ((parsed_locale.language == 0) || (parsed_locale.script == 0) || (parsed_locale.region == 0))
  98. return {};
  99. auto locale_without_script = ByteString::formatted("{}-{}",
  100. cldr.unique_strings.get(parsed_locale.language),
  101. cldr.unique_strings.get(parsed_locale.region));
  102. if (cldr.locales.contains(locale_without_script))
  103. return {};
  104. if (find_alias(locale_without_script) != cldr.locale_aliases.end())
  105. return {};
  106. if (auto it = find_alias(locale); it != cldr.locale_aliases.end())
  107. cldr.locale_aliases.append({ it->name, locale_without_script });
  108. else
  109. cldr.locale_aliases.append({ locale, locale_without_script });
  110. return {};
  111. };
  112. for (auto const& locale : cldr.locales)
  113. TRY(append_alias_without_script(locale.key));
  114. for (auto const& locale : cldr.locale_aliases)
  115. TRY(append_alias_without_script(locale.alias));
  116. return {};
  117. }
  118. static ErrorOr<void> parse_all_locales(ByteString core_path, ByteString numbers_path, CLDR& cldr)
  119. {
  120. LexicalPath core_supplemental_path(core_path);
  121. core_supplemental_path = core_supplemental_path.append("supplemental"sv);
  122. VERIFY(FileSystem::is_directory(core_supplemental_path.string()));
  123. auto remove_variants_from_path = [&](ByteString path) -> ErrorOr<ByteString> {
  124. auto parsed_locale = TRY(CanonicalLanguageID::parse(cldr.unique_strings, LexicalPath::basename(path)));
  125. StringBuilder builder;
  126. builder.append(cldr.unique_strings.get(parsed_locale.language));
  127. if (auto script = cldr.unique_strings.get(parsed_locale.script); !script.is_empty())
  128. builder.appendff("-{}", script);
  129. if (auto region = cldr.unique_strings.get(parsed_locale.region); !region.is_empty())
  130. builder.appendff("-{}", region);
  131. return builder.to_byte_string();
  132. };
  133. TRY(Core::Directory::for_each_entry(TRY(String::formatted("{}/main", numbers_path)), Core::DirIterator::SkipParentAndBaseDir, [&](auto& entry, auto& directory) -> ErrorOr<IterationDecision> {
  134. auto numbers_path = LexicalPath::join(directory.path().string(), entry.name).string();
  135. auto language = TRY(remove_variants_from_path(numbers_path));
  136. cldr.locales.ensure(language);
  137. return IterationDecision::Continue;
  138. }));
  139. TRY(parse_default_content_locales(move(core_path), cldr));
  140. TRY(define_aliases_without_scripts(cldr));
  141. return {};
  142. }
  143. static ErrorOr<void> generate_unicode_locale_header(Core::InputBufferedFile& file, CLDR& cldr)
  144. {
  145. StringBuilder builder;
  146. SourceGenerator generator { builder };
  147. generator.append(R"~~~(
  148. #pragma once
  149. #include <AK/Types.h>
  150. namespace Locale {
  151. )~~~");
  152. auto locales = cldr.locales.keys();
  153. generate_enum(generator, format_identifier, "Locale"sv, "None"sv, locales, cldr.locale_aliases);
  154. generator.append(R"~~~(
  155. }
  156. )~~~");
  157. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  158. return {};
  159. }
  160. static ErrorOr<void> generate_unicode_locale_implementation(Core::InputBufferedFile& file, CLDR& cldr)
  161. {
  162. auto string_index_type = cldr.unique_strings.type_that_fits();
  163. StringBuilder builder;
  164. SourceGenerator generator { builder };
  165. generator.set("string_index_type"sv, string_index_type);
  166. generator.set("locales_size"sv, ByteString::number(cldr.locales.size()));
  167. generator.append(R"~~~(
  168. #include <AK/Array.h>
  169. #include <AK/BinarySearch.h>
  170. #include <AK/Optional.h>
  171. #include <AK/Span.h>
  172. #include <AK/String.h>
  173. #include <AK/StringView.h>
  174. #include <AK/Vector.h>
  175. #include <LibLocale/DateTimeFormat.h>
  176. #include <LibLocale/Locale.h>
  177. #include <LibLocale/LocaleData.h>
  178. #include <LibUnicode/CurrencyCode.h>
  179. namespace Locale {
  180. )~~~");
  181. auto locales = cldr.locales.keys();
  182. quick_sort(locales);
  183. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) -> ErrorOr<void> {
  184. HashValueMap<ByteString> hashes;
  185. TRY(hashes.try_ensure_capacity(values.size()));
  186. for (auto const& value : values)
  187. hashes.set(value.hash(), format_identifier(enum_title, value));
  188. for (auto const& alias : aliases)
  189. hashes.set(alias.alias.hash(), format_identifier(enum_title, alias.alias));
  190. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  191. return {};
  192. };
  193. TRY(append_from_string("Locale"sv, "locale"sv, cldr.locales.keys(), cldr.locale_aliases));
  194. generator.append(R"~~~(
  195. }
  196. )~~~");
  197. TRY(file.write_until_depleted(generator.as_string_view().bytes()));
  198. return {};
  199. }
  200. ErrorOr<int> serenity_main(Main::Arguments arguments)
  201. {
  202. StringView generated_header_path;
  203. StringView generated_implementation_path;
  204. StringView core_path;
  205. StringView numbers_path;
  206. Core::ArgsParser args_parser;
  207. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  208. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  209. args_parser.add_option(core_path, "Path to cldr-core directory", "core-path", 'r', "core-path");
  210. args_parser.add_option(numbers_path, "Path to cldr-numbers directory", "numbers-path", 'n', "numbers-path");
  211. args_parser.parse(arguments);
  212. auto generated_header_file = TRY(open_file(generated_header_path, Core::File::OpenMode::Write));
  213. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::File::OpenMode::Write));
  214. CLDR cldr;
  215. TRY(parse_all_locales(core_path, numbers_path, cldr));
  216. TRY(generate_unicode_locale_header(*generated_header_file, cldr));
  217. TRY(generate_unicode_locale_implementation(*generated_implementation_file, cldr));
  218. return 0;
  219. }