GenerateUnicodeNumberFormat.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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 {
  610. )~~~");
  611. locale_data.unique_strings.generate(generator);
  612. generator.append(R"~~~(
  613. struct NumberFormatImpl {
  614. NumberFormat to_unicode_number_format() const {
  615. NumberFormat number_format {};
  616. number_format.magnitude = magnitude;
  617. number_format.exponent = exponent;
  618. number_format.plurality = static_cast<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, "NumberFormatImpl"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_{}", nullptr, [&](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_{}", nullptr, [&](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, NumericSymbol symbol)
  694. {
  695. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr) {
  696. auto symbols = s_numeric_symbol_lists.at(number_system->symbols);
  697. auto symbol_index = to_underlying(symbol);
  698. if (symbol_index >= symbols.size())
  699. return {};
  700. return s_string_list[symbols[symbol_index]];
  701. }
  702. return {};
  703. }
  704. Optional<NumberGroupings> get_number_system_groupings(StringView locale, StringView system)
  705. {
  706. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr)
  707. return NumberGroupings { number_system->primary_grouping_size, number_system->secondary_grouping_size };
  708. return {};
  709. }
  710. Optional<NumberFormat> get_standard_number_system_format(StringView locale, StringView system, StandardNumberFormatType type)
  711. {
  712. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr) {
  713. @number_format_index_type@ format_index = 0;
  714. switch (type) {
  715. case StandardNumberFormatType::Decimal:
  716. format_index = number_system->decimal_format;
  717. break;
  718. case StandardNumberFormatType::Currency:
  719. format_index = number_system->currency_format;
  720. break;
  721. case StandardNumberFormatType::Accounting:
  722. format_index = number_system->accounting_format;
  723. break;
  724. case StandardNumberFormatType::Percent:
  725. format_index = number_system->percent_format;
  726. break;
  727. case StandardNumberFormatType::Scientific:
  728. format_index = number_system->scientific_format;
  729. break;
  730. }
  731. return s_number_formats[format_index].to_unicode_number_format();
  732. }
  733. return {};
  734. }
  735. Vector<NumberFormat> get_compact_number_system_formats(StringView locale, StringView system, CompactNumberFormatType type)
  736. {
  737. Vector<NumberFormat> formats;
  738. if (auto const* number_system = find_number_system(locale, system); number_system != nullptr) {
  739. @number_format_list_index_type@ number_format_list_index { 0 };
  740. switch (type) {
  741. case CompactNumberFormatType::DecimalLong:
  742. number_format_list_index = number_system->decimal_long_formats;
  743. break;
  744. case CompactNumberFormatType::DecimalShort:
  745. number_format_list_index = number_system->decimal_short_formats;
  746. break;
  747. case CompactNumberFormatType::CurrencyUnit:
  748. number_format_list_index = number_system->currency_unit_formats;
  749. break;
  750. case CompactNumberFormatType::CurrencyShort:
  751. number_format_list_index = number_system->currency_short_formats;
  752. break;
  753. }
  754. auto number_formats = s_number_format_lists.at(number_format_list_index);
  755. formats.ensure_capacity(number_formats.size());
  756. for (auto number_format : number_formats)
  757. formats.append(s_number_formats[number_format].to_unicode_number_format());
  758. }
  759. return formats;
  760. }
  761. static Unit const* find_units(StringView locale, StringView unit)
  762. {
  763. auto locale_value = locale_from_string(locale);
  764. if (!locale_value.has_value())
  765. return nullptr;
  766. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  767. auto const& locale_units = s_locale_units.at(locale_index);
  768. for (auto unit_index : locale_units) {
  769. auto const& units = s_units.at(unit_index);
  770. if (unit == s_string_list[units.unit])
  771. return &units;
  772. };
  773. return nullptr;
  774. }
  775. Vector<NumberFormat> get_unit_formats(StringView locale, StringView unit, Style style)
  776. {
  777. Vector<NumberFormat> formats;
  778. if (auto const* units = find_units(locale, unit); units != nullptr) {
  779. @number_format_list_index_type@ number_format_list_index { 0 };
  780. switch (style) {
  781. case Style::Long:
  782. number_format_list_index = units->long_formats;
  783. break;
  784. case Style::Short:
  785. number_format_list_index = units->short_formats;
  786. break;
  787. case Style::Narrow:
  788. number_format_list_index = units->narrow_formats;
  789. break;
  790. default:
  791. VERIFY_NOT_REACHED();
  792. }
  793. auto number_formats = s_number_format_lists.at(number_format_list_index);
  794. formats.ensure_capacity(number_formats.size());
  795. for (auto number_format : number_formats)
  796. formats.append(s_number_formats[number_format].to_unicode_number_format());
  797. }
  798. return formats;
  799. }
  800. }
  801. )~~~");
  802. VERIFY(file.write(generator.as_string_view()));
  803. }
  804. ErrorOr<int> serenity_main(Main::Arguments arguments)
  805. {
  806. StringView generated_header_path = nullptr;
  807. StringView generated_implementation_path = nullptr;
  808. StringView numbers_path = nullptr;
  809. StringView units_path = nullptr;
  810. Core::ArgsParser args_parser;
  811. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  812. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  813. args_parser.add_option(numbers_path, "Path to cldr-numbers directory", "numbers-path", 'n', "numbers-path");
  814. args_parser.add_option(units_path, "Path to cldr-units directory", "units-path", 'u', "units-path");
  815. args_parser.parse(arguments);
  816. auto open_file = [&](StringView path) -> ErrorOr<NonnullRefPtr<Core::File>> {
  817. if (path.is_empty()) {
  818. args_parser.print_usage(stderr, arguments.argv[0]);
  819. return Error::from_string_literal("Must provide all command line options"sv);
  820. }
  821. return Core::File::open(path, Core::OpenMode::ReadWrite);
  822. };
  823. auto generated_header_file = TRY(open_file(generated_header_path));
  824. auto generated_implementation_file = TRY(open_file(generated_implementation_path));
  825. UnicodeLocaleData locale_data;
  826. TRY(parse_all_locales(numbers_path, units_path, locale_data));
  827. generate_unicode_locale_header(generated_header_file, locale_data);
  828. generate_unicode_locale_implementation(generated_implementation_file, locale_data);
  829. return 0;
  830. }