GenerateUnicodeNumberFormat.cpp 40 KB

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