GenerateUnicodeNumberFormat.cpp 42 KB

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