GenerateUnicodeNumberFormat.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  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/CharacterTypes.h>
  10. #include <AK/Find.h>
  11. #include <AK/Format.h>
  12. #include <AK/HashFunctions.h>
  13. #include <AK/HashMap.h>
  14. #include <AK/JsonObject.h>
  15. #include <AK/JsonParser.h>
  16. #include <AK/JsonValue.h>
  17. #include <AK/LexicalPath.h>
  18. #include <AK/QuickSort.h>
  19. #include <AK/SourceGenerator.h>
  20. #include <AK/String.h>
  21. #include <AK/StringBuilder.h>
  22. #include <AK/Traits.h>
  23. #include <AK/Utf8View.h>
  24. #include <LibCore/ArgsParser.h>
  25. #include <LibCore/DirIterator.h>
  26. #include <LibCore/File.h>
  27. #include <LibUnicode/Locale.h>
  28. #include <LibUnicode/NumberFormat.h>
  29. #include <math.h>
  30. using StringIndexType = u16;
  31. constexpr auto s_string_index_type = "u16"sv;
  32. using NumberFormatIndexType = u16;
  33. constexpr auto s_number_format_index_type = "u16"sv;
  34. enum class NumberFormatType {
  35. Standard,
  36. Compact,
  37. };
  38. struct NumberFormat : public Unicode::NumberFormat {
  39. using Base = Unicode::NumberFormat;
  40. static Base::Plurality plurality_from_string(StringView plurality)
  41. {
  42. if (plurality == "other"sv)
  43. return Base::Plurality::Other;
  44. if (plurality == "1"sv)
  45. return Base::Plurality::Single;
  46. if (plurality == "zero"sv)
  47. return Base::Plurality::Zero;
  48. if (plurality == "one"sv)
  49. return Base::Plurality::One;
  50. if (plurality == "two"sv)
  51. return Base::Plurality::Two;
  52. if (plurality == "few"sv)
  53. return Base::Plurality::Few;
  54. if (plurality == "many"sv)
  55. return Base::Plurality::Many;
  56. VERIFY_NOT_REACHED();
  57. }
  58. unsigned hash() const
  59. {
  60. auto hash = pair_int_hash(magnitude, exponent);
  61. hash = pair_int_hash(hash, static_cast<u8>(plurality));
  62. hash = pair_int_hash(hash, zero_format_index);
  63. hash = pair_int_hash(hash, positive_format_index);
  64. hash = pair_int_hash(hash, negative_format_index);
  65. for (auto index : identifier_indices)
  66. hash = pair_int_hash(hash, index);
  67. return hash;
  68. }
  69. bool operator==(NumberFormat const& other) const
  70. {
  71. return (magnitude == other.magnitude)
  72. && (exponent == other.exponent)
  73. && (plurality == other.plurality)
  74. && (zero_format_index == other.zero_format_index)
  75. && (positive_format_index == other.positive_format_index)
  76. && (negative_format_index == other.negative_format_index)
  77. && (identifier_indices == other.identifier_indices);
  78. }
  79. StringIndexType zero_format_index { 0 };
  80. StringIndexType positive_format_index { 0 };
  81. StringIndexType negative_format_index { 0 };
  82. Vector<StringIndexType> identifier_indices {};
  83. };
  84. template<>
  85. struct AK::Formatter<NumberFormat> : Formatter<FormatString> {
  86. ErrorOr<void> format(FormatBuilder& builder, NumberFormat const& format)
  87. {
  88. StringBuilder identifier_indices;
  89. identifier_indices.join(", "sv, format.identifier_indices);
  90. return Formatter<FormatString>::format(builder,
  91. "{{ {}, {}, {}, {}, {}, {}, {{ {} }} }}",
  92. format.magnitude,
  93. format.exponent,
  94. static_cast<u8>(format.plurality),
  95. format.zero_format_index,
  96. format.positive_format_index,
  97. format.negative_format_index,
  98. identifier_indices.build());
  99. }
  100. };
  101. template<>
  102. struct AK::Traits<NumberFormat> : public GenericTraits<NumberFormat> {
  103. static unsigned hash(NumberFormat const& f) { return f.hash(); }
  104. };
  105. struct NumberSystem {
  106. StringIndexType system { 0 };
  107. HashMap<String, StringIndexType> symbols {};
  108. u8 primary_grouping_size { 0 };
  109. u8 secondary_grouping_size { 0 };
  110. NumberFormatIndexType decimal_format { 0 };
  111. Vector<NumberFormatIndexType> decimal_long_formats {};
  112. Vector<NumberFormatIndexType> decimal_short_formats {};
  113. NumberFormatIndexType currency_format { 0 };
  114. NumberFormatIndexType accounting_format { 0 };
  115. Vector<NumberFormatIndexType> currency_unit_formats {};
  116. Vector<NumberFormatIndexType> currency_short_formats {};
  117. NumberFormatIndexType percent_format { 0 };
  118. NumberFormatIndexType scientific_format { 0 };
  119. };
  120. struct Unit {
  121. StringIndexType unit { 0 };
  122. Vector<NumberFormatIndexType> long_formats {};
  123. Vector<NumberFormatIndexType> short_formats {};
  124. Vector<NumberFormatIndexType> narrow_formats {};
  125. };
  126. struct Locale {
  127. HashMap<String, NumberSystem> number_systems;
  128. HashMap<String, Unit> units {};
  129. };
  130. struct UnicodeLocaleData {
  131. UniqueStringStorage<StringIndexType> unique_strings;
  132. UniqueStorage<NumberFormat, NumberFormatIndexType> unique_formats;
  133. HashMap<String, Locale> locales;
  134. Vector<String> numeric_symbols;
  135. size_t max_identifier_count { 0 };
  136. };
  137. static String parse_identifiers(String pattern, StringView replacement, UnicodeLocaleData& locale_data, NumberFormat& format)
  138. {
  139. static Utf8View whitespace { "\u0020\u00a0\u200f"sv };
  140. while (true) {
  141. Utf8View utf8_pattern { pattern };
  142. Optional<size_t> start_index;
  143. Optional<size_t> end_index;
  144. bool inside_replacement = false;
  145. for (auto it = utf8_pattern.begin(); it != utf8_pattern.end(); ++it) {
  146. if (*it == '{') {
  147. if (start_index.has_value()) {
  148. end_index = utf8_pattern.byte_offset_of(it);
  149. break;
  150. }
  151. inside_replacement = true;
  152. } else if (*it == '}') {
  153. inside_replacement = false;
  154. } else if (!inside_replacement && !start_index.has_value() && !whitespace.contains(*it)) {
  155. start_index = utf8_pattern.byte_offset_of(it);
  156. }
  157. }
  158. if (!start_index.has_value())
  159. return pattern;
  160. end_index = end_index.value_or(pattern.length());
  161. utf8_pattern = utf8_pattern.substring_view(*start_index, *end_index - *start_index);
  162. utf8_pattern = utf8_pattern.trim(whitespace);
  163. auto identifier = utf8_pattern.as_string().replace("'.'"sv, "."sv);
  164. auto identifier_index = locale_data.unique_strings.ensure(move(identifier));
  165. size_t replacement_index = 0;
  166. if (auto index = format.identifier_indices.find_first_index(identifier_index); index.has_value()) {
  167. replacement_index = *index;
  168. } else {
  169. replacement_index = format.identifier_indices.size();
  170. format.identifier_indices.append(identifier_index);
  171. locale_data.max_identifier_count = max(locale_data.max_identifier_count, format.identifier_indices.size());
  172. }
  173. pattern = String::formatted("{}{{{}:{}}}{}",
  174. *start_index > 0 ? pattern.substring_view(0, *start_index) : ""sv,
  175. replacement,
  176. replacement_index,
  177. pattern.substring_view(*start_index + utf8_pattern.byte_length()));
  178. }
  179. }
  180. static void parse_number_pattern(Vector<String> patterns, UnicodeLocaleData& locale_data, NumberFormatType type, NumberFormat& format, NumberSystem* number_system_for_groupings = nullptr)
  181. {
  182. // https://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns
  183. // https://cldr.unicode.org/translation/number-currency-formats/number-and-currency-patterns
  184. VERIFY((patterns.size() == 1) || (patterns.size() == 2));
  185. auto replace_patterns = [&](String pattern) {
  186. static HashMap<StringView, StringView> replacements = {
  187. { "{0}"sv, "{number}"sv },
  188. { "{1}"sv, "{currency}"sv },
  189. { "%"sv, "{percentSign}"sv },
  190. { "+"sv, "{plusSign}"sv },
  191. { "-"sv, "{minusSign}"sv },
  192. { "¤"sv, "{currency}"sv }, // U+00A4 Currency Sign
  193. { "E"sv, "{scientificSeparator}"sv },
  194. };
  195. for (auto const& replacement : replacements)
  196. pattern = pattern.replace(replacement.key, replacement.value, true);
  197. if (auto start_number_index = pattern.find_any_of("#0"sv, String::SearchDirection::Forward); start_number_index.has_value()) {
  198. auto end_number_index = *start_number_index + 1;
  199. for (; end_number_index < pattern.length(); ++end_number_index) {
  200. auto ch = pattern[end_number_index];
  201. if ((ch != '#') && (ch != '0') && (ch != ',') && (ch != '.'))
  202. break;
  203. }
  204. if (number_system_for_groupings) {
  205. auto number_pattern = pattern.substring_view(*start_number_index, end_number_index - *start_number_index);
  206. auto group_separators = number_pattern.find_all(","sv);
  207. VERIFY((group_separators.size() == 1) || (group_separators.size() == 2));
  208. auto decimal = number_pattern.find('.');
  209. VERIFY(decimal.has_value());
  210. if (group_separators.size() == 1) {
  211. number_system_for_groupings->primary_grouping_size = *decimal - group_separators[0] - 1;
  212. number_system_for_groupings->secondary_grouping_size = number_system_for_groupings->primary_grouping_size;
  213. } else {
  214. number_system_for_groupings->primary_grouping_size = *decimal - group_separators[1] - 1;
  215. number_system_for_groupings->secondary_grouping_size = group_separators[1] - group_separators[0] - 1;
  216. }
  217. }
  218. pattern = String::formatted("{}{{number}}{}",
  219. *start_number_index > 0 ? pattern.substring_view(0, *start_number_index) : ""sv,
  220. pattern.substring_view(end_number_index));
  221. // This is specifically handled here rather than in the replacements HashMap above so
  222. // that we do not errantly replace zeroes in number patterns.
  223. if (pattern.contains(*replacements.get("E"sv)))
  224. pattern = pattern.replace("0"sv, "{scientificExponent}"sv);
  225. }
  226. if (type == NumberFormatType::Compact)
  227. return parse_identifiers(move(pattern), "compactIdentifier"sv, locale_data, format);
  228. return pattern;
  229. };
  230. auto zero_format = replace_patterns(move(patterns[0]));
  231. format.positive_format_index = locale_data.unique_strings.ensure(String::formatted("{{plusSign}}{}", zero_format));
  232. if (patterns.size() == 2) {
  233. auto negative_format = replace_patterns(move(patterns[1]));
  234. format.negative_format_index = locale_data.unique_strings.ensure(move(negative_format));
  235. } else {
  236. format.negative_format_index = locale_data.unique_strings.ensure(String::formatted("{{minusSign}}{}", zero_format));
  237. }
  238. format.zero_format_index = locale_data.unique_strings.ensure(move(zero_format));
  239. }
  240. static void parse_number_pattern(Vector<String> patterns, UnicodeLocaleData& locale_data, NumberFormatType type, NumberFormatIndexType& format_index, NumberSystem* number_system_for_groupings = nullptr)
  241. {
  242. NumberFormat format {};
  243. parse_number_pattern(move(patterns), locale_data, type, format, number_system_for_groupings);
  244. format_index = locale_data.unique_formats.ensure(move(format));
  245. }
  246. static ErrorOr<void> parse_number_systems(String locale_numbers_path, UnicodeLocaleData& locale_data, Locale& locale)
  247. {
  248. LexicalPath numbers_path(move(locale_numbers_path));
  249. numbers_path = numbers_path.append("numbers.json"sv);
  250. auto numbers_file = TRY(Core::File::open(numbers_path.string(), Core::OpenMode::ReadOnly));
  251. auto numbers = TRY(JsonValue::from_string(numbers_file->read_all()));
  252. auto const& main_object = numbers.as_object().get("main"sv);
  253. auto const& locale_object = main_object.as_object().get(numbers_path.parent().basename());
  254. auto const& locale_numbers_object = locale_object.as_object().get("numbers"sv);
  255. auto ensure_number_system = [&](auto const& system) -> NumberSystem& {
  256. return locale.number_systems.ensure(system, [&]() {
  257. auto system_index = locale_data.unique_strings.ensure(system);
  258. return NumberSystem { .system = system_index };
  259. });
  260. };
  261. auto parse_number_format = [&](auto const& format_object) {
  262. Vector<NumberFormatIndexType> result;
  263. result.ensure_capacity(format_object.size());
  264. format_object.for_each_member([&](auto const& key, JsonValue const& value) {
  265. auto split_key = key.split_view('-');
  266. if (split_key.size() != 3)
  267. return;
  268. auto patterns = value.as_string().split(';');
  269. NumberFormat format {};
  270. if (auto type = split_key[0].template to_uint<u64>(); type.has_value()) {
  271. VERIFY(*type % 10 == 0);
  272. format.magnitude = static_cast<u8>(log10(*type));
  273. if (patterns[0] != "0"sv) {
  274. auto number_of_zeroes_in_pattern = patterns[0].count("0"sv);
  275. VERIFY(format.magnitude >= number_of_zeroes_in_pattern);
  276. format.exponent = format.magnitude + 1 - number_of_zeroes_in_pattern;
  277. }
  278. } else {
  279. VERIFY(split_key[0] == "unitPattern"sv);
  280. }
  281. format.plurality = NumberFormat::plurality_from_string(split_key[2]);
  282. parse_number_pattern(move(patterns), locale_data, NumberFormatType::Compact, format);
  283. auto format_index = locale_data.unique_formats.ensure(move(format));
  284. result.append(format_index);
  285. });
  286. return result;
  287. };
  288. locale_numbers_object.as_object().for_each_member([&](auto const& key, JsonValue const& value) {
  289. constexpr auto symbols_prefix = "symbols-numberSystem-"sv;
  290. constexpr auto decimal_formats_prefix = "decimalFormats-numberSystem-"sv;
  291. constexpr auto currency_formats_prefix = "currencyFormats-numberSystem-"sv;
  292. constexpr auto percent_formats_prefix = "percentFormats-numberSystem-"sv;
  293. constexpr auto scientific_formats_prefix = "scientificFormats-numberSystem-"sv;
  294. if (key.starts_with(symbols_prefix)) {
  295. auto system = key.substring(symbols_prefix.length());
  296. auto& number_system = ensure_number_system(system);
  297. value.as_object().for_each_member([&](auto const& symbol, JsonValue const& localization) {
  298. auto symbol_index = locale_data.unique_strings.ensure(localization.as_string());
  299. number_system.symbols.set(symbol, symbol_index);
  300. if (!locale_data.numeric_symbols.contains_slow(symbol))
  301. locale_data.numeric_symbols.append(symbol);
  302. });
  303. } else if (key.starts_with(decimal_formats_prefix)) {
  304. auto system = key.substring(decimal_formats_prefix.length());
  305. auto& number_system = ensure_number_system(system);
  306. auto format_object = value.as_object().get("standard"sv);
  307. parse_number_pattern(format_object.as_string().split(';'), locale_data, NumberFormatType::Standard, number_system.decimal_format, &number_system);
  308. auto const& long_format = value.as_object().get("long"sv).as_object().get("decimalFormat"sv);
  309. number_system.decimal_long_formats = parse_number_format(long_format.as_object());
  310. auto const& short_format = value.as_object().get("short"sv).as_object().get("decimalFormat"sv);
  311. number_system.decimal_short_formats = parse_number_format(short_format.as_object());
  312. } else if (key.starts_with(currency_formats_prefix)) {
  313. auto system = key.substring(currency_formats_prefix.length());
  314. auto& number_system = ensure_number_system(system);
  315. auto format_object = value.as_object().get("standard"sv);
  316. parse_number_pattern(format_object.as_string().split(';'), locale_data, NumberFormatType::Standard, number_system.currency_format);
  317. format_object = value.as_object().get("accounting"sv);
  318. parse_number_pattern(format_object.as_string().split(';'), locale_data, NumberFormatType::Standard, number_system.accounting_format);
  319. number_system.currency_unit_formats = parse_number_format(value.as_object());
  320. if (value.as_object().has("short"sv)) {
  321. auto const& short_format = value.as_object().get("short"sv).as_object().get("standard"sv);
  322. number_system.currency_short_formats = parse_number_format(short_format.as_object());
  323. }
  324. } else if (key.starts_with(percent_formats_prefix)) {
  325. auto system = key.substring(percent_formats_prefix.length());
  326. auto& number_system = ensure_number_system(system);
  327. auto format_object = value.as_object().get("standard"sv);
  328. parse_number_pattern(format_object.as_string().split(';'), locale_data, NumberFormatType::Standard, number_system.percent_format);
  329. } else if (key.starts_with(scientific_formats_prefix)) {
  330. auto system = key.substring(scientific_formats_prefix.length());
  331. auto& number_system = ensure_number_system(system);
  332. auto format_object = value.as_object().get("standard"sv);
  333. parse_number_pattern(format_object.as_string().split(';'), locale_data, NumberFormatType::Standard, number_system.scientific_format);
  334. }
  335. });
  336. return {};
  337. }
  338. static ErrorOr<void> parse_units(String locale_units_path, UnicodeLocaleData& locale_data, Locale& locale)
  339. {
  340. LexicalPath units_path(move(locale_units_path));
  341. units_path = units_path.append("units.json"sv);
  342. auto units_file = TRY(Core::File::open(units_path.string(), Core::OpenMode::ReadOnly));
  343. auto units = TRY(JsonValue::from_string(units_file->read_all()));
  344. auto const& main_object = units.as_object().get("main"sv);
  345. auto const& locale_object = main_object.as_object().get(units_path.parent().basename());
  346. auto const& locale_units_object = locale_object.as_object().get("units"sv);
  347. auto const& long_object = locale_units_object.as_object().get("long"sv);
  348. auto const& short_object = locale_units_object.as_object().get("short"sv);
  349. auto const& narrow_object = locale_units_object.as_object().get("narrow"sv);
  350. auto ensure_unit = [&](auto const& unit) -> Unit& {
  351. return locale.units.ensure(unit, [&]() {
  352. auto unit_index = locale_data.unique_strings.ensure(unit);
  353. return Unit { .unit = unit_index };
  354. });
  355. };
  356. auto is_sanctioned_unit = [](StringView unit_name) {
  357. // This is a copy of the units sanctioned for use within ECMA-402. LibUnicode generally tries to
  358. // avoid being directly dependent on ECMA-402, but this rather significantly reduces the amount
  359. // of data generated here, and ECMA-402 is currently the only consumer of this data.
  360. // https://tc39.es/ecma402/#table-sanctioned-simple-unit-identifiers
  361. constexpr auto sanctioned_units = AK::Array { "acre"sv, "bit"sv, "byte"sv, "celsius"sv, "centimeter"sv, "day"sv, "degree"sv, "fahrenheit"sv, "fluid-ounce"sv, "foot"sv, "gallon"sv, "gigabit"sv, "gigabyte"sv, "gram"sv, "hectare"sv, "hour"sv, "inch"sv, "kilobit"sv, "kilobyte"sv, "kilogram"sv, "kilometer"sv, "liter"sv, "megabit"sv, "megabyte"sv, "meter"sv, "mile"sv, "mile-scandinavian"sv, "milliliter"sv, "millimeter"sv, "millisecond"sv, "minute"sv, "month"sv, "ounce"sv, "percent"sv, "petabyte"sv, "pound"sv, "second"sv, "stone"sv, "terabit"sv, "terabyte"sv, "week"sv, "yard"sv, "year"sv };
  362. return find(sanctioned_units.begin(), sanctioned_units.end(), unit_name) != sanctioned_units.end();
  363. };
  364. auto parse_units_object = [&](auto const& units_object, Unicode::Style style) {
  365. constexpr auto unit_pattern_prefix = "unitPattern-count-"sv;
  366. constexpr auto combined_unit_separator = "-per-"sv;
  367. units_object.for_each_member([&](auto const& key, JsonValue const& value) {
  368. auto end_of_category = key.find('-');
  369. if (!end_of_category.has_value())
  370. return;
  371. auto unit_name = key.substring(*end_of_category + 1);
  372. if (!is_sanctioned_unit(unit_name)) {
  373. auto indices = unit_name.find_all(combined_unit_separator);
  374. if (indices.size() != 1)
  375. return;
  376. auto numerator = unit_name.substring_view(0, indices[0]);
  377. auto denominator = unit_name.substring_view(indices[0] + combined_unit_separator.length());
  378. if (!is_sanctioned_unit(numerator) || !is_sanctioned_unit(denominator))
  379. return;
  380. }
  381. value.as_object().for_each_member([&](auto const& unit_key, JsonValue const& pattern_value) {
  382. if (!unit_key.starts_with(unit_pattern_prefix))
  383. return;
  384. auto& unit = ensure_unit(unit_name);
  385. NumberFormat format {};
  386. auto plurality = unit_key.substring_view(unit_pattern_prefix.length());
  387. format.plurality = NumberFormat::plurality_from_string(plurality);
  388. auto zero_format = pattern_value.as_string().replace("{0}"sv, "{number}"sv);
  389. zero_format = parse_identifiers(zero_format, "unitIdentifier"sv, locale_data, format);
  390. format.positive_format_index = locale_data.unique_strings.ensure(zero_format.replace("{number}"sv, "{plusSign}{number}"sv));
  391. format.negative_format_index = locale_data.unique_strings.ensure(zero_format.replace("{number}"sv, "{minusSign}{number}"sv));
  392. format.zero_format_index = locale_data.unique_strings.ensure(move(zero_format));
  393. auto format_index = locale_data.unique_formats.ensure(move(format));
  394. switch (style) {
  395. case Unicode::Style::Long:
  396. unit.long_formats.append(format_index);
  397. break;
  398. case Unicode::Style::Short:
  399. unit.short_formats.append(format_index);
  400. break;
  401. case Unicode::Style::Narrow:
  402. unit.narrow_formats.append(format_index);
  403. break;
  404. default:
  405. VERIFY_NOT_REACHED();
  406. }
  407. });
  408. });
  409. };
  410. parse_units_object(long_object.as_object(), Unicode::Style::Long);
  411. parse_units_object(short_object.as_object(), Unicode::Style::Short);
  412. parse_units_object(narrow_object.as_object(), Unicode::Style::Narrow);
  413. return {};
  414. }
  415. static ErrorOr<void> parse_all_locales(String numbers_path, String units_path, UnicodeLocaleData& locale_data)
  416. {
  417. auto numbers_iterator = TRY(path_to_dir_iterator(move(numbers_path)));
  418. auto units_iterator = TRY(path_to_dir_iterator(move(units_path)));
  419. auto remove_variants_from_path = [&](String path) -> ErrorOr<String> {
  420. auto parsed_locale = TRY(CanonicalLanguageID<StringIndexType>::parse(locale_data.unique_strings, LexicalPath::basename(path)));
  421. StringBuilder builder;
  422. builder.append(locale_data.unique_strings.get(parsed_locale.language));
  423. if (auto script = locale_data.unique_strings.get(parsed_locale.script); !script.is_empty())
  424. builder.appendff("-{}", script);
  425. if (auto region = locale_data.unique_strings.get(parsed_locale.region); !region.is_empty())
  426. builder.appendff("-{}", region);
  427. return builder.build();
  428. };
  429. while (numbers_iterator.has_next()) {
  430. auto numbers_path = TRY(next_path_from_dir_iterator(numbers_iterator));
  431. auto language = TRY(remove_variants_from_path(numbers_path));
  432. auto& locale = locale_data.locales.ensure(language);
  433. TRY(parse_number_systems(numbers_path, locale_data, locale));
  434. }
  435. while (units_iterator.has_next()) {
  436. auto units_path = TRY(next_path_from_dir_iterator(units_iterator));
  437. auto language = TRY(remove_variants_from_path(units_path));
  438. auto& locale = locale_data.locales.ensure(language);
  439. TRY(parse_units(units_path, locale_data, locale));
  440. }
  441. return {};
  442. }
  443. static String format_identifier(StringView owner, String identifier)
  444. {
  445. identifier = identifier.replace("-"sv, "_"sv, true);
  446. if (all_of(identifier, is_ascii_digit))
  447. return String::formatted("{}_{}", owner[0], identifier);
  448. if (is_ascii_lower_alpha(identifier[0]))
  449. return String::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  450. return identifier;
  451. }
  452. static void generate_unicode_locale_header(Core::File& file, UnicodeLocaleData& locale_data)
  453. {
  454. StringBuilder builder;
  455. SourceGenerator generator { builder };
  456. generator.append(R"~~~(
  457. #pragma once
  458. #include <AK/Optional.h>
  459. #include <AK/StringView.h>
  460. #include <AK/Types.h>
  461. #include <AK/Vector.h>
  462. #include <LibUnicode/Forward.h>
  463. namespace Unicode {
  464. )~~~");
  465. generate_enum(generator, format_identifier, "NumericSymbol"sv, {}, locale_data.numeric_symbols);
  466. generator.append(R"~~~(
  467. namespace Detail {
  468. Optional<StringView> get_number_system_symbol(StringView locale, StringView system, StringView numeric_symbol);
  469. Optional<NumberGroupings> get_number_system_groupings(StringView locale, StringView system);
  470. Optional<NumberFormat> get_standard_number_system_format(StringView locale, StringView system, StandardNumberFormatType type);
  471. Vector<NumberFormat> get_compact_number_system_formats(StringView locale, StringView system, CompactNumberFormatType type);
  472. Vector<Unicode::NumberFormat> get_unit_formats(StringView locale, StringView unit, Style style);
  473. Optional<NumericSymbol> numeric_symbol_from_string(StringView numeric_symbol);
  474. }
  475. }
  476. )~~~");
  477. VERIFY(file.write(generator.as_string_view()));
  478. }
  479. static void generate_unicode_locale_implementation(Core::File& file, UnicodeLocaleData& locale_data)
  480. {
  481. StringBuilder builder;
  482. SourceGenerator generator { builder };
  483. generator.set("string_index_type"sv, s_string_index_type);
  484. generator.set("number_format_index_type"sv, s_number_format_index_type);
  485. generator.set("numeric_symbols_size", String::number(locale_data.numeric_symbols.size()));
  486. generator.set("identifier_count", String::number(locale_data.max_identifier_count));
  487. generator.append(R"~~~(
  488. #include <AK/Array.h>
  489. #include <AK/BinarySearch.h>
  490. #include <AK/Span.h>
  491. #include <LibUnicode/Locale.h>
  492. #include <LibUnicode/NumberFormat.h>
  493. #include <LibUnicode/UnicodeNumberFormat.h>
  494. namespace Unicode::Detail {
  495. )~~~");
  496. locale_data.unique_strings.generate(generator);
  497. generator.append(R"~~~(
  498. struct NumberFormat {
  499. Unicode::NumberFormat to_unicode_number_format() const {
  500. Unicode::NumberFormat number_format {};
  501. number_format.magnitude = magnitude;
  502. number_format.exponent = exponent;
  503. number_format.plurality = static_cast<Unicode::NumberFormat::Plurality>(plurality);
  504. number_format.zero_format = s_string_list[zero_format];
  505. number_format.positive_format = s_string_list[positive_format];
  506. number_format.negative_format = s_string_list[negative_format];
  507. number_format.identifiers.ensure_capacity(identifiers.size());
  508. for (@string_index_type@ identifier : identifiers)
  509. number_format.identifiers.append(s_string_list[identifier]);
  510. return number_format;
  511. }
  512. u8 magnitude { 0 };
  513. u8 exponent { 0 };
  514. u8 plurality { 0 };
  515. @string_index_type@ zero_format { 0 };
  516. @string_index_type@ positive_format { 0 };
  517. @string_index_type@ negative_format { 0 };
  518. Array<@string_index_type@, @identifier_count@> identifiers {};
  519. };
  520. struct NumberSystem {
  521. @string_index_type@ system { 0 };
  522. Array<@string_index_type@, @numeric_symbols_size@> symbols {};
  523. u8 primary_grouping_size { 0 };
  524. u8 secondary_grouping_size { 0 };
  525. @number_format_index_type@ decimal_format { 0 };
  526. Span<@number_format_index_type@ const> decimal_long_formats {};
  527. Span<@number_format_index_type@ const> decimal_short_formats {};
  528. @number_format_index_type@ currency_format { 0 };
  529. @number_format_index_type@ accounting_format { 0 };
  530. Span<@number_format_index_type@ const> currency_unit_formats {};
  531. Span<@number_format_index_type@ const> currency_short_formats {};
  532. @number_format_index_type@ percent_format { 0 };
  533. @number_format_index_type@ scientific_format { 0 };
  534. };
  535. struct Unit {
  536. @string_index_type@ unit { 0 };
  537. Span<@number_format_index_type@ const> long_formats {};
  538. Span<@number_format_index_type@ const> short_formats {};
  539. Span<@number_format_index_type@ const> narrow_formats {};
  540. };
  541. )~~~");
  542. locale_data.unique_formats.generate(generator, "NumberFormat"sv, "s_number_formats"sv, 10);
  543. auto append_number_formats = [&](String name, auto const& number_formats) {
  544. generator.set("name"sv, move(name));
  545. generator.set("size"sv, String::number(number_formats.size()));
  546. generator.append(R"~~~(
  547. static constexpr Array<@number_format_index_type@, @size@> @name@ { {)~~~");
  548. bool first = true;
  549. for (auto number_format : number_formats) {
  550. generator.append(first ? " " : ", ");
  551. generator.append(String::number(number_format));
  552. first = false;
  553. }
  554. generator.append(" } };");
  555. };
  556. auto append_number_systems = [&](String name, auto const& number_systems) {
  557. auto format_name = [&](StringView system, StringView format) {
  558. return String::formatted("{}_{}_{}", name, system, format);
  559. };
  560. for (auto const& number_system : number_systems) {
  561. append_number_formats(format_name(number_system.key, "dl"sv), number_system.value.decimal_long_formats);
  562. append_number_formats(format_name(number_system.key, "ds"sv), number_system.value.decimal_short_formats);
  563. append_number_formats(format_name(number_system.key, "cu"sv), number_system.value.currency_unit_formats);
  564. append_number_formats(format_name(number_system.key, "cs"sv), number_system.value.currency_short_formats);
  565. }
  566. generator.set("name", name);
  567. generator.set("size", String::number(number_systems.size()));
  568. generator.append(R"~~~(
  569. static constexpr Array<NumberSystem, @size@> @name@ { {)~~~");
  570. for (auto const& number_system : number_systems) {
  571. generator.set("system"sv, String::number(number_system.value.system));
  572. generator.set("primary_grouping_size"sv, String::number(number_system.value.primary_grouping_size));
  573. generator.set("secondary_grouping_size"sv, String::number(number_system.value.secondary_grouping_size));
  574. generator.set("decimal_format", String::number(number_system.value.decimal_format));
  575. generator.set("decimal_long_formats"sv, format_name(number_system.key, "dl"sv));
  576. generator.set("decimal_short_formats"sv, format_name(number_system.key, "ds"sv));
  577. generator.set("currency_format", String::number(number_system.value.currency_format));
  578. generator.set("accounting_format", String::number(number_system.value.accounting_format));
  579. generator.set("currency_unit_formats"sv, format_name(number_system.key, "cu"sv));
  580. generator.set("currency_short_formats"sv, format_name(number_system.key, "cs"sv));
  581. generator.set("percent_format", String::number(number_system.value.percent_format));
  582. generator.set("scientific_format", String::number(number_system.value.scientific_format));
  583. generator.append(R"~~~(
  584. { @system@, {)~~~");
  585. for (auto const& symbol : locale_data.numeric_symbols) {
  586. auto index = number_system.value.symbols.get(symbol).value_or(0);
  587. generator.set("index", String::number(index));
  588. generator.append(" @index@,");
  589. }
  590. generator.append(" }, @primary_grouping_size@, @secondary_grouping_size@, ");
  591. generator.append("@decimal_format@, @decimal_long_formats@.span(), @decimal_short_formats@.span(), ");
  592. generator.append("@currency_format@, @accounting_format@, @currency_unit_formats@.span(), @currency_short_formats@.span(), ");
  593. generator.append("@percent_format@, @scientific_format@ },");
  594. }
  595. generator.append(R"~~~(
  596. } };
  597. )~~~");
  598. };
  599. auto append_units = [&](String name, auto const& units) {
  600. auto format_name = [&](String unit, StringView format) {
  601. unit = unit.replace("-"sv, "_"sv, true);
  602. return String::formatted("{}_{}_{}", name, unit, format);
  603. };
  604. for (auto const& unit : units) {
  605. append_number_formats(format_name(unit.key, "l"sv), unit.value.long_formats);
  606. append_number_formats(format_name(unit.key, "s"sv), unit.value.short_formats);
  607. append_number_formats(format_name(unit.key, "n"sv), unit.value.narrow_formats);
  608. }
  609. generator.set("name", name);
  610. generator.set("size", String::number(units.size()));
  611. generator.append(R"~~~(
  612. static constexpr Array<Unit, @size@> @name@ { {)~~~");
  613. for (auto const& unit : units) {
  614. generator.set("unit"sv, String::number(unit.value.unit));
  615. generator.set("long_formats"sv, format_name(unit.key, "l"sv));
  616. generator.set("short_formats"sv, format_name(unit.key, "s"sv));
  617. generator.set("narrow_formats"sv, format_name(unit.key, "n"sv));
  618. generator.append(R"~~~(
  619. { @unit@, @long_formats@.span(), @short_formats@.span(), @narrow_formats@.span() },)~~~");
  620. }
  621. generator.append(R"~~~(
  622. } };
  623. )~~~");
  624. };
  625. generate_mapping(generator, locale_data.locales, "NumberSystem"sv, "s_number_systems"sv, "s_number_systems_{}", [&](auto const& name, auto const& value) { append_number_systems(name, value.number_systems); });
  626. generate_mapping(generator, locale_data.locales, "Unit"sv, "s_units"sv, "s_units_{}", [&](auto const& name, auto const& value) { append_units(name, value.units); });
  627. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& values) {
  628. HashValueMap<String> hashes;
  629. hashes.ensure_capacity(values.size());
  630. for (auto const& value : values)
  631. hashes.set(value.hash(), format_identifier(enum_title, value));
  632. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  633. };
  634. append_from_string("NumericSymbol"sv, "numeric_symbol"sv, locale_data.numeric_symbols);
  635. generator.append(R"~~~(
  636. static NumberSystem const* find_number_system(StringView locale, StringView system)
  637. {
  638. auto locale_value = locale_from_string(locale);
  639. if (!locale_value.has_value())
  640. return nullptr;
  641. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  642. auto const& number_systems = s_number_systems.at(locale_index);
  643. for (auto const& number_system : number_systems) {
  644. if (system == s_string_list[number_system.system])
  645. return &number_system;
  646. };
  647. return nullptr;
  648. }
  649. Optional<StringView> get_number_system_symbol(StringView locale, StringView system, StringView symbol)
  650. {
  651. auto symbol_value = numeric_symbol_from_string(symbol);
  652. if (!symbol_value.has_value())
  653. return {};
  654. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr) {
  655. auto symbol_index = to_underlying(*symbol_value);
  656. return s_string_list[number_system->symbols[symbol_index]];
  657. }
  658. return {};
  659. }
  660. Optional<NumberGroupings> get_number_system_groupings(StringView locale, StringView system)
  661. {
  662. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr)
  663. return NumberGroupings { number_system->primary_grouping_size, number_system->secondary_grouping_size };
  664. return {};
  665. }
  666. Optional<Unicode::NumberFormat> get_standard_number_system_format(StringView locale, StringView system, StandardNumberFormatType type)
  667. {
  668. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr) {
  669. @number_format_index_type@ format_index = 0;
  670. switch (type) {
  671. case StandardNumberFormatType::Decimal:
  672. format_index = number_system->decimal_format;
  673. break;
  674. case StandardNumberFormatType::Currency:
  675. format_index = number_system->currency_format;
  676. break;
  677. case StandardNumberFormatType::Accounting:
  678. format_index = number_system->accounting_format;
  679. break;
  680. case StandardNumberFormatType::Percent:
  681. format_index = number_system->percent_format;
  682. break;
  683. case StandardNumberFormatType::Scientific:
  684. format_index = number_system->scientific_format;
  685. break;
  686. }
  687. return s_number_formats[format_index].to_unicode_number_format();
  688. }
  689. return {};
  690. }
  691. Vector<Unicode::NumberFormat> get_compact_number_system_formats(StringView locale, StringView system, CompactNumberFormatType type)
  692. {
  693. Vector<Unicode::NumberFormat> formats;
  694. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr) {
  695. Span<@number_format_index_type@ const> number_formats;
  696. switch (type) {
  697. case CompactNumberFormatType::DecimalLong:
  698. number_formats = number_system->decimal_long_formats;
  699. break;
  700. case CompactNumberFormatType::DecimalShort:
  701. number_formats = number_system->decimal_short_formats;
  702. break;
  703. case CompactNumberFormatType::CurrencyUnit:
  704. number_formats = number_system->currency_unit_formats;
  705. break;
  706. case CompactNumberFormatType::CurrencyShort:
  707. number_formats = number_system->currency_short_formats;
  708. break;
  709. }
  710. formats.ensure_capacity(number_formats.size());
  711. for (auto number_format : number_formats)
  712. formats.append(s_number_formats[number_format].to_unicode_number_format());
  713. }
  714. return formats;
  715. }
  716. static Unit const* find_units(StringView locale, StringView unit)
  717. {
  718. auto locale_value = locale_from_string(locale);
  719. if (!locale_value.has_value())
  720. return nullptr;
  721. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  722. auto const& locale_units = s_units.at(locale_index);
  723. for (auto const& units : locale_units) {
  724. if (unit == s_string_list[units.unit])
  725. return &units;
  726. };
  727. return nullptr;
  728. }
  729. Vector<Unicode::NumberFormat> get_unit_formats(StringView locale, StringView unit, Style style)
  730. {
  731. Vector<Unicode::NumberFormat> formats;
  732. if (auto const* units = find_units(locale, unit); units != nullptr) {
  733. Span<@number_format_index_type@ const> number_formats;
  734. switch (style) {
  735. case Style::Long:
  736. number_formats = units->long_formats;
  737. break;
  738. case Style::Short:
  739. number_formats = units->short_formats;
  740. break;
  741. case Style::Narrow:
  742. number_formats = units->narrow_formats;
  743. break;
  744. default:
  745. VERIFY_NOT_REACHED();
  746. }
  747. formats.ensure_capacity(number_formats.size());
  748. for (auto number_format : number_formats)
  749. formats.append(s_number_formats[number_format].to_unicode_number_format());
  750. }
  751. return formats;
  752. }
  753. }
  754. )~~~");
  755. VERIFY(file.write(generator.as_string_view()));
  756. }
  757. ErrorOr<int> serenity_main(Main::Arguments arguments)
  758. {
  759. StringView generated_header_path = nullptr;
  760. StringView generated_implementation_path = nullptr;
  761. StringView numbers_path = nullptr;
  762. StringView units_path = nullptr;
  763. Core::ArgsParser args_parser;
  764. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  765. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  766. args_parser.add_option(numbers_path, "Path to cldr-numbers directory", "numbers-path", 'n', "numbers-path");
  767. args_parser.add_option(units_path, "Path to cldr-units directory", "units-path", 'u', "units-path");
  768. args_parser.parse(arguments);
  769. auto open_file = [&](StringView path) -> ErrorOr<NonnullRefPtr<Core::File>> {
  770. if (path.is_empty()) {
  771. args_parser.print_usage(stderr, arguments.argv[0]);
  772. return Error::from_string_literal("Must provide all command line options"sv);
  773. }
  774. return Core::File::open(path, Core::OpenMode::ReadWrite);
  775. };
  776. auto generated_header_file = TRY(open_file(generated_header_path));
  777. auto generated_implementation_file = TRY(open_file(generated_implementation_path));
  778. UnicodeLocaleData locale_data;
  779. TRY(parse_all_locales(numbers_path, units_path, locale_data));
  780. generate_unicode_locale_header(generated_header_file, locale_data);
  781. generate_unicode_locale_implementation(generated_implementation_file, locale_data);
  782. return 0;
  783. }