GenerateUnicodeDateTimeFormat.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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/CharacterTypes.h>
  9. #include <AK/Format.h>
  10. #include <AK/GenericLexer.h>
  11. #include <AK/HashFunctions.h>
  12. #include <AK/HashMap.h>
  13. #include <AK/JsonObject.h>
  14. #include <AK/JsonParser.h>
  15. #include <AK/JsonValue.h>
  16. #include <AK/LexicalPath.h>
  17. #include <AK/SourceGenerator.h>
  18. #include <AK/String.h>
  19. #include <AK/StringBuilder.h>
  20. #include <AK/Traits.h>
  21. #include <AK/Utf8View.h>
  22. #include <LibCore/ArgsParser.h>
  23. #include <LibCore/DirIterator.h>
  24. #include <LibCore/File.h>
  25. #include <LibUnicode/DateTimeFormat.h>
  26. using StringIndexType = u16;
  27. constexpr auto s_string_index_type = "u16"sv;
  28. using CalendarPatternIndexType = u16;
  29. constexpr auto s_calendar_pattern_index_type = "u16"sv;
  30. struct CalendarPattern : public Unicode::CalendarPattern {
  31. bool contains_only_date_fields() const
  32. {
  33. return !day_period.has_value() && !hour.has_value() && !minute.has_value() && !second.has_value() && !fractional_second_digits.has_value() && !time_zone_name.has_value();
  34. }
  35. bool contains_only_time_fields() const
  36. {
  37. return !weekday.has_value() && !era.has_value() && !year.has_value() && !month.has_value() && !day.has_value();
  38. }
  39. unsigned hash() const
  40. {
  41. auto hash = pair_int_hash(pattern_index, pattern12_index);
  42. auto hash_field = [&](auto const& field) {
  43. if (field.has_value())
  44. hash = pair_int_hash(hash, static_cast<u8>(*field));
  45. else
  46. hash = pair_int_hash(hash, -1);
  47. };
  48. hash_field(era);
  49. hash_field(year);
  50. hash_field(month);
  51. hash_field(weekday);
  52. hash_field(day);
  53. hash_field(day_period);
  54. hash_field(hour);
  55. hash_field(minute);
  56. hash_field(second);
  57. hash_field(fractional_second_digits);
  58. hash_field(time_zone_name);
  59. return hash;
  60. }
  61. bool operator==(CalendarPattern const& other) const
  62. {
  63. return (pattern_index == other.pattern_index)
  64. && (pattern12_index == other.pattern12_index)
  65. && (era == other.era)
  66. && (year == other.year)
  67. && (month == other.month)
  68. && (weekday == other.weekday)
  69. && (day == other.day)
  70. && (day_period == other.day_period)
  71. && (hour == other.hour)
  72. && (minute == other.minute)
  73. && (second == other.second)
  74. && (fractional_second_digits == other.fractional_second_digits)
  75. && (time_zone_name == other.time_zone_name);
  76. }
  77. StringIndexType pattern_index { 0 };
  78. StringIndexType pattern12_index { 0 };
  79. };
  80. template<>
  81. struct AK::Formatter<CalendarPattern> : Formatter<FormatString> {
  82. ErrorOr<void> format(FormatBuilder& builder, CalendarPattern const& pattern)
  83. {
  84. auto field_to_i8 = [](auto const& field) -> i8 {
  85. if (!field.has_value())
  86. return -1;
  87. return static_cast<i8>(*field);
  88. };
  89. return Formatter<FormatString>::format(builder,
  90. "{{ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} }}",
  91. pattern.pattern_index,
  92. pattern.pattern12_index,
  93. field_to_i8(pattern.era),
  94. field_to_i8(pattern.year),
  95. field_to_i8(pattern.month),
  96. field_to_i8(pattern.weekday),
  97. field_to_i8(pattern.day),
  98. field_to_i8(pattern.day_period),
  99. field_to_i8(pattern.hour),
  100. field_to_i8(pattern.minute),
  101. field_to_i8(pattern.second),
  102. field_to_i8(pattern.fractional_second_digits),
  103. field_to_i8(pattern.time_zone_name));
  104. }
  105. };
  106. template<>
  107. struct AK::Traits<CalendarPattern> : public GenericTraits<CalendarPattern> {
  108. static unsigned hash(CalendarPattern const& c) { return c.hash(); }
  109. };
  110. struct CalendarFormat {
  111. CalendarPatternIndexType full_format { 0 };
  112. CalendarPatternIndexType long_format { 0 };
  113. CalendarPatternIndexType medium_format { 0 };
  114. CalendarPatternIndexType short_format { 0 };
  115. };
  116. struct Calendar {
  117. StringIndexType calendar { 0 };
  118. CalendarFormat date_formats {};
  119. CalendarFormat time_formats {};
  120. CalendarFormat date_time_formats {};
  121. Vector<CalendarPatternIndexType> available_formats {};
  122. };
  123. struct Locale {
  124. HashMap<String, Calendar> calendars;
  125. };
  126. struct UnicodeLocaleData {
  127. UniqueStringStorage<StringIndexType> unique_strings;
  128. UniqueStorage<CalendarPattern, CalendarPatternIndexType> unique_patterns;
  129. HashMap<String, Locale> locales;
  130. HashMap<String, Vector<Unicode::HourCycle>> hour_cycles;
  131. Vector<String> hour_cycle_regions;
  132. Vector<String> calendars;
  133. Vector<Alias> calendar_aliases {
  134. // FIXME: Aliases should come from BCP47. See: https://unicode-org.atlassian.net/browse/CLDR-15158
  135. { "gregorian"sv, "gregory"sv },
  136. };
  137. };
  138. static ErrorOr<void> parse_hour_cycles(String core_path, UnicodeLocaleData& locale_data)
  139. {
  140. // https://unicode.org/reports/tr35/tr35-dates.html#Time_Data
  141. LexicalPath time_data_path(move(core_path));
  142. time_data_path = time_data_path.append("supplemental"sv);
  143. time_data_path = time_data_path.append("timeData.json"sv);
  144. auto time_data_file = TRY(Core::File::open(time_data_path.string(), Core::OpenMode::ReadOnly));
  145. auto time_data = TRY(JsonValue::from_string(time_data_file->read_all()));
  146. auto const& supplemental_object = time_data.as_object().get("supplemental"sv);
  147. auto const& time_data_object = supplemental_object.as_object().get("timeData"sv);
  148. auto parse_hour_cycle = [](StringView hour_cycle) -> Optional<Unicode::HourCycle> {
  149. if (hour_cycle == "h"sv)
  150. return Unicode::HourCycle::H12;
  151. if (hour_cycle == "H"sv)
  152. return Unicode::HourCycle::H23;
  153. if (hour_cycle == "K"sv)
  154. return Unicode::HourCycle::H11;
  155. if (hour_cycle == "k"sv)
  156. return Unicode::HourCycle::H24;
  157. return {};
  158. };
  159. time_data_object.as_object().for_each_member([&](auto const& key, JsonValue const& value) {
  160. auto allowed_hour_cycles_string = value.as_object().get("_allowed"sv).as_string();
  161. auto allowed_hour_cycles = allowed_hour_cycles_string.split_view(' ');
  162. Vector<Unicode::HourCycle> hour_cycles;
  163. for (auto allowed_hour_cycle : allowed_hour_cycles) {
  164. if (auto hour_cycle = parse_hour_cycle(allowed_hour_cycle); hour_cycle.has_value())
  165. hour_cycles.append(*hour_cycle);
  166. }
  167. locale_data.hour_cycles.set(key, move(hour_cycles));
  168. if (!locale_data.hour_cycle_regions.contains_slow(key))
  169. locale_data.hour_cycle_regions.append(key);
  170. });
  171. return {};
  172. };
  173. static constexpr auto is_char(char ch)
  174. {
  175. return [ch](auto c) { return c == ch; };
  176. }
  177. // For patterns that are 12-hour aware, we need to generate two patterns: one with the day period
  178. // (e.g. {ampm}) in the pattern, and one without the day period. We need to take care to remove
  179. // extra spaces around the day period. Some example expected removals:
  180. //
  181. // "{hour}:{minute} {ampm}" becomes "{hour}:{minute}" (remove the space before {ampm})
  182. // "{ampm} {hour}" becomes "{hour}" (remove the space after {ampm})
  183. // "{hour}:{minute} {ampm} {timeZoneName}" becomes "{hour}:{minute} {timeZoneName}" (remove one of the spaces around {ampm})
  184. static String remove_period_from_pattern(String pattern)
  185. {
  186. for (auto remove : AK::Array { "({ampm})"sv, "{ampm}"sv, "({dayPeriod})"sv, "{dayPeriod}"sv }) {
  187. auto index = pattern.find(remove);
  188. if (!index.has_value())
  189. continue;
  190. constexpr u32 space = ' ';
  191. constexpr u32 open = '{';
  192. constexpr u32 close = '}';
  193. Utf8View utf8_pattern { pattern };
  194. Optional<u32> before_removal;
  195. Optional<u32> after_removal;
  196. for (auto it = utf8_pattern.begin(); utf8_pattern.byte_offset_of(it) < *index; ++it)
  197. before_removal = *it;
  198. if (auto it = utf8_pattern.iterator_at_byte_offset(*index + remove.length()); it != utf8_pattern.end())
  199. after_removal = *it;
  200. if ((before_removal == space) && (after_removal != open)) {
  201. pattern = String::formatted("{}{}",
  202. pattern.substring_view(0, *index - 1),
  203. pattern.substring_view(*index + remove.length()));
  204. } else if ((after_removal == space) && (before_removal != close)) {
  205. pattern = String::formatted("{}{}",
  206. pattern.substring_view(0, *index),
  207. pattern.substring_view(*index + remove.length() + 1));
  208. } else {
  209. pattern = String::formatted("{}{}",
  210. pattern.substring_view(0, *index),
  211. pattern.substring_view(*index + remove.length()));
  212. }
  213. }
  214. return pattern;
  215. }
  216. static Optional<CalendarPatternIndexType> parse_date_time_pattern(String pattern, UnicodeLocaleData& locale_data)
  217. {
  218. // https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
  219. using Unicode::CalendarPatternStyle;
  220. CalendarPattern format {};
  221. GenericLexer lexer { pattern };
  222. StringBuilder builder;
  223. bool hour12 { false };
  224. while (!lexer.is_eof()) {
  225. // Literal strings enclosed by quotes are to be appended to the pattern as-is without further
  226. // processing (this just avoids conflicts with the patterns below).
  227. if (lexer.next_is(is_quote)) {
  228. builder.append(lexer.consume_quoted_string());
  229. continue;
  230. }
  231. auto starting_char = lexer.peek();
  232. auto segment = lexer.consume_while([&](char ch) { return ch == starting_char; });
  233. // Era
  234. if (all_of(segment, is_char('G'))) {
  235. builder.append("{era}");
  236. if (segment.length() <= 3)
  237. format.era = CalendarPatternStyle::Short;
  238. else if (segment.length() == 4)
  239. format.era = CalendarPatternStyle::Long;
  240. else
  241. format.era = CalendarPatternStyle::Narrow;
  242. }
  243. // Year
  244. else if (all_of(segment, is_any_of("yYuUr"sv))) {
  245. builder.append("{year}");
  246. if (segment.length() == 2)
  247. format.year = CalendarPatternStyle::TwoDigit;
  248. else
  249. format.year = CalendarPatternStyle::Numeric;
  250. }
  251. // Quarter
  252. else if (all_of(segment, is_any_of("qQ"sv))) {
  253. // Intl.DateTimeFormat does not support quarter formatting, so drop these patterns.
  254. return {};
  255. }
  256. // Month
  257. else if (all_of(segment, is_any_of("ML"sv))) {
  258. builder.append("{month}");
  259. if (segment.length() == 1)
  260. format.month = CalendarPatternStyle::Numeric;
  261. else if (segment.length() == 2)
  262. format.month = CalendarPatternStyle::TwoDigit;
  263. else if (segment.length() == 3)
  264. format.month = CalendarPatternStyle::Short;
  265. else if (segment.length() == 4)
  266. format.month = CalendarPatternStyle::Long;
  267. else if (segment.length() == 5)
  268. format.month = CalendarPatternStyle::Narrow;
  269. } else if (all_of(segment, is_char('l'))) {
  270. // Using 'l' for month formatting is deprecated by TR-35, ensure it is not used.
  271. return {};
  272. }
  273. // Week
  274. else if (all_of(segment, is_any_of("wW"sv))) {
  275. // Intl.DateTimeFormat does not support week formatting, so drop these patterns.
  276. return {};
  277. }
  278. // Day
  279. else if (all_of(segment, is_char('d'))) {
  280. builder.append("{day}");
  281. if (segment.length() == 1)
  282. format.day = CalendarPatternStyle::Numeric;
  283. else
  284. format.day = CalendarPatternStyle::TwoDigit;
  285. } else if (all_of(segment, is_any_of("DFG"sv))) {
  286. builder.append("{day}");
  287. format.day = CalendarPatternStyle::Numeric;
  288. }
  289. // Weekday
  290. else if (all_of(segment, is_char('E'))) {
  291. builder.append("{weekday}");
  292. if (segment.length() == 4)
  293. format.weekday = CalendarPatternStyle::Long;
  294. else if (segment.length() == 5)
  295. format.weekday = CalendarPatternStyle::Narrow;
  296. else
  297. format.weekday = CalendarPatternStyle::Short;
  298. } else if (all_of(segment, is_any_of("ec"sv))) {
  299. builder.append("{weekday}");
  300. // TR-35 defines "e", "c", and "cc" as as numeric, and "ee" as 2-digit, but those
  301. // pattern styles are not supported by Intl.DateTimeFormat.
  302. if (segment.length() <= 2)
  303. return {};
  304. if (segment.length() == 4)
  305. format.weekday = CalendarPatternStyle::Long;
  306. else if (segment.length() == 5)
  307. format.weekday = CalendarPatternStyle::Narrow;
  308. else
  309. format.weekday = CalendarPatternStyle::Short;
  310. }
  311. // Period
  312. else if (all_of(segment, is_any_of("ab"sv))) {
  313. builder.append("{ampm}");
  314. hour12 = true;
  315. if (segment.length() == 4)
  316. format.day_period = CalendarPatternStyle::Long;
  317. else if (segment.length() == 5)
  318. format.day_period = CalendarPatternStyle::Narrow;
  319. else
  320. format.day_period = CalendarPatternStyle::Short;
  321. } else if (all_of(segment, is_char('B'))) {
  322. builder.append("{dayPeriod}");
  323. hour12 = true;
  324. if (segment.length() == 4)
  325. format.day_period = CalendarPatternStyle::Long;
  326. else if (segment.length() == 5)
  327. format.day_period = CalendarPatternStyle::Narrow;
  328. else
  329. format.day_period = CalendarPatternStyle::Short;
  330. }
  331. // Hour
  332. else if (all_of(segment, is_any_of("hHKk"sv))) {
  333. builder.append("{hour}");
  334. if ((segment[0] == 'h') || (segment[0] == 'K'))
  335. hour12 = true;
  336. if (segment.length() == 1)
  337. format.hour = CalendarPatternStyle::Numeric;
  338. else
  339. format.hour = CalendarPatternStyle::TwoDigit;
  340. } else if (all_of(segment, is_any_of("jJC"sv))) {
  341. // TR-35 indicates these should not be used.
  342. return {};
  343. }
  344. // Minute
  345. else if (all_of(segment, is_char('m'))) {
  346. builder.append("{minute}");
  347. if (segment.length() == 1)
  348. format.minute = CalendarPatternStyle::Numeric;
  349. else
  350. format.minute = CalendarPatternStyle::TwoDigit;
  351. }
  352. // Second
  353. else if (all_of(segment, is_char('s'))) {
  354. builder.append("{second}");
  355. if (segment.length() == 1)
  356. format.second = CalendarPatternStyle::Numeric;
  357. else
  358. format.second = CalendarPatternStyle::TwoDigit;
  359. } else if (all_of(segment, is_char('S'))) {
  360. builder.append("{fractionalSecondDigits}");
  361. VERIFY(segment.length() <= 3);
  362. format.fractional_second_digits = static_cast<u8>(segment.length());
  363. } else if (all_of(segment, is_char('A'))) {
  364. // Intl.DateTimeFormat does not support millisecond formatting, so drop these patterns.
  365. return {};
  366. }
  367. // Zone
  368. else if (all_of(segment, is_any_of("zZOvVXx"))) {
  369. builder.append("{timeZoneName}");
  370. if (segment.length() < 4)
  371. format.time_zone_name = CalendarPatternStyle::Short;
  372. else
  373. format.time_zone_name = CalendarPatternStyle::Long;
  374. }
  375. // Non-patterns
  376. else {
  377. builder.append(segment);
  378. }
  379. }
  380. pattern = builder.build();
  381. if (hour12) {
  382. auto pattern_without_period = remove_period_from_pattern(pattern);
  383. format.pattern_index = locale_data.unique_strings.ensure(move(pattern_without_period));
  384. format.pattern12_index = locale_data.unique_strings.ensure(move(pattern));
  385. } else {
  386. format.pattern_index = locale_data.unique_strings.ensure(move(pattern));
  387. }
  388. return locale_data.unique_patterns.ensure(move(format));
  389. }
  390. static void generate_missing_patterns(Calendar& calendar, Vector<CalendarPattern> date_formats, Vector<CalendarPattern> time_formats, UnicodeLocaleData& locale_data)
  391. {
  392. // https://unicode.org/reports/tr35/tr35-dates.html#Missing_Skeleton_Fields
  393. auto replace_pattern = [&](auto format, auto time_format, auto date_format) {
  394. auto pattern = locale_data.unique_strings.get(format);
  395. auto time_pattern = locale_data.unique_strings.get(time_format);
  396. auto date_pattern = locale_data.unique_strings.get(date_format);
  397. auto new_pattern = pattern.replace("{0}", time_pattern).replace("{1}", date_pattern);
  398. return locale_data.unique_strings.ensure(move(new_pattern));
  399. };
  400. auto append_if_unique = [&](auto format) {
  401. auto format_index = locale_data.unique_patterns.ensure(move(format));
  402. if (!calendar.available_formats.contains_slow(format_index))
  403. calendar.available_formats.append(format_index);
  404. };
  405. for (auto const& format : date_formats)
  406. append_if_unique(format);
  407. for (auto const& format : time_formats)
  408. append_if_unique(format);
  409. for (auto const& date_format : date_formats) {
  410. CalendarPatternIndexType date_time_format_index = 0;
  411. if (date_format.month == Unicode::CalendarPatternStyle::Long) {
  412. if (date_format.weekday.has_value())
  413. date_time_format_index = calendar.date_time_formats.full_format;
  414. else
  415. date_time_format_index = calendar.date_time_formats.long_format;
  416. } else if (date_format.month == Unicode::CalendarPatternStyle::Short) {
  417. date_time_format_index = calendar.date_time_formats.medium_format;
  418. } else {
  419. date_time_format_index = calendar.date_time_formats.short_format;
  420. }
  421. for (auto const& time_format : time_formats) {
  422. auto format = locale_data.unique_patterns.get(date_time_format_index);
  423. if (time_format.pattern12_index != 0)
  424. format.pattern12_index = replace_pattern(format.pattern_index, time_format.pattern12_index, date_format.pattern_index);
  425. format.pattern_index = replace_pattern(format.pattern_index, time_format.pattern_index, date_format.pattern_index);
  426. format.for_each_calendar_field_zipped_with(date_format, [](auto& field, auto const& date_field) {
  427. if (date_field.has_value())
  428. field = date_field;
  429. });
  430. format.for_each_calendar_field_zipped_with(time_format, [](auto& field, auto const& time_field) {
  431. if (time_field.has_value())
  432. field = time_field;
  433. });
  434. append_if_unique(move(format));
  435. }
  436. }
  437. }
  438. static ErrorOr<void> parse_calendars(String locale_calendars_path, UnicodeLocaleData& locale_data, Locale& locale)
  439. {
  440. LexicalPath calendars_path(move(locale_calendars_path));
  441. if (!calendars_path.basename().starts_with("ca-"sv))
  442. return {};
  443. auto calendars_file = TRY(Core::File::open(calendars_path.string(), Core::OpenMode::ReadOnly));
  444. auto calendars = TRY(JsonValue::from_string(calendars_file->read_all()));
  445. auto const& main_object = calendars.as_object().get("main"sv);
  446. auto const& locale_object = main_object.as_object().get(calendars_path.parent().basename());
  447. auto const& dates_object = locale_object.as_object().get("dates"sv);
  448. auto const& calendars_object = dates_object.as_object().get("calendars"sv);
  449. auto ensure_calendar = [&](auto const& calendar) -> Calendar& {
  450. return locale.calendars.ensure(calendar, [&]() {
  451. auto calendar_index = locale_data.unique_strings.ensure(calendar);
  452. return Calendar { .calendar = calendar_index };
  453. });
  454. };
  455. auto parse_patterns = [&](auto& formats, auto const& patterns_object, Vector<CalendarPattern>* patterns) {
  456. auto parse_pattern = [&](auto name) {
  457. auto format = patterns_object.get(name);
  458. auto format_index = parse_date_time_pattern(format.as_string(), locale_data).value();
  459. if (patterns)
  460. patterns->append(locale_data.unique_patterns.get(format_index));
  461. return format_index;
  462. };
  463. formats.full_format = parse_pattern("full"sv);
  464. formats.long_format = parse_pattern("long"sv);
  465. formats.medium_format = parse_pattern("medium"sv);
  466. formats.short_format = parse_pattern("short"sv);
  467. };
  468. calendars_object.as_object().for_each_member([&](auto const& calendar_name, JsonValue const& value) {
  469. // The generic calendar is not a supported Unicode calendar key, so skip it:
  470. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#unicode_calendar_keys
  471. if (calendar_name == "generic"sv)
  472. return;
  473. auto& calendar = ensure_calendar(calendar_name);
  474. if (!locale_data.calendars.contains_slow(calendar_name))
  475. locale_data.calendars.append(calendar_name);
  476. Vector<CalendarPattern> date_formats;
  477. Vector<CalendarPattern> time_formats;
  478. auto const& date_formats_object = value.as_object().get("dateFormats"sv);
  479. parse_patterns(calendar.date_formats, date_formats_object.as_object(), &date_formats);
  480. auto const& time_formats_object = value.as_object().get("timeFormats"sv);
  481. parse_patterns(calendar.time_formats, time_formats_object.as_object(), &time_formats);
  482. auto const& date_time_formats_object = value.as_object().get("dateTimeFormats"sv);
  483. parse_patterns(calendar.date_time_formats, date_time_formats_object.as_object(), nullptr);
  484. auto const& available_formats = date_time_formats_object.as_object().get("availableFormats"sv);
  485. available_formats.as_object().for_each_member([&](auto const&, JsonValue const& pattern) {
  486. auto pattern_index = parse_date_time_pattern(pattern.as_string(), locale_data);
  487. if (!pattern_index.has_value())
  488. return;
  489. auto const& format = locale_data.unique_patterns.get(*pattern_index);
  490. if (format.contains_only_date_fields())
  491. date_formats.append(format);
  492. else if (format.contains_only_time_fields())
  493. time_formats.append(format);
  494. if (!calendar.available_formats.contains_slow(*pattern_index))
  495. calendar.available_formats.append(*pattern_index);
  496. });
  497. generate_missing_patterns(calendar, move(date_formats), move(time_formats), locale_data);
  498. });
  499. return {};
  500. }
  501. static ErrorOr<void> parse_all_locales(String core_path, String dates_path, UnicodeLocaleData& locale_data)
  502. {
  503. TRY(parse_hour_cycles(move(core_path), locale_data));
  504. auto dates_iterator = TRY(path_to_dir_iterator(move(dates_path)));
  505. auto remove_variants_from_path = [&](String path) -> ErrorOr<String> {
  506. auto parsed_locale = TRY(CanonicalLanguageID<StringIndexType>::parse(locale_data.unique_strings, LexicalPath::basename(path)));
  507. StringBuilder builder;
  508. builder.append(locale_data.unique_strings.get(parsed_locale.language));
  509. if (auto script = locale_data.unique_strings.get(parsed_locale.script); !script.is_empty())
  510. builder.appendff("-{}", script);
  511. if (auto region = locale_data.unique_strings.get(parsed_locale.region); !region.is_empty())
  512. builder.appendff("-{}", region);
  513. return builder.build();
  514. };
  515. while (dates_iterator.has_next()) {
  516. auto dates_path = TRY(next_path_from_dir_iterator(dates_iterator));
  517. auto calendars_iterator = TRY(path_to_dir_iterator(dates_path, {}));
  518. auto language = TRY(remove_variants_from_path(dates_path));
  519. auto& locale = locale_data.locales.ensure(language);
  520. while (calendars_iterator.has_next()) {
  521. auto calendars_path = TRY(next_path_from_dir_iterator(calendars_iterator));
  522. TRY(parse_calendars(move(calendars_path), locale_data, locale));
  523. }
  524. }
  525. return {};
  526. }
  527. static String format_identifier(StringView owner, String identifier)
  528. {
  529. identifier = identifier.replace("-"sv, "_"sv, true);
  530. if (all_of(identifier, is_ascii_digit))
  531. return String::formatted("{}_{}", owner[0], identifier);
  532. if (is_ascii_lower_alpha(identifier[0]))
  533. return String::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  534. return identifier;
  535. }
  536. static void generate_unicode_locale_header(Core::File& file, UnicodeLocaleData& locale_data)
  537. {
  538. StringBuilder builder;
  539. SourceGenerator generator { builder };
  540. generator.append(R"~~~(
  541. #pragma once
  542. #include <AK/Optional.h>
  543. #include <AK/StringView.h>
  544. #include <LibUnicode/Forward.h>
  545. namespace Unicode {
  546. )~~~");
  547. generate_enum(generator, format_identifier, "Calendar"sv, {}, locale_data.calendars, locale_data.calendar_aliases);
  548. generate_enum(generator, format_identifier, "HourCycleRegion"sv, {}, locale_data.hour_cycle_regions);
  549. generator.append(R"~~~(
  550. namespace Detail {
  551. Optional<Calendar> calendar_from_string(StringView calendar);
  552. Optional<HourCycleRegion> hour_cycle_region_from_string(StringView hour_cycle_region);
  553. Vector<Unicode::HourCycle> get_regional_hour_cycles(StringView region);
  554. Optional<Unicode::CalendarFormat> get_calendar_date_format(StringView locale, StringView calendar);
  555. Optional<Unicode::CalendarFormat> get_calendar_time_format(StringView locale, StringView calendar);
  556. Optional<Unicode::CalendarFormat> get_calendar_date_time_format(StringView locale, StringView calendar);
  557. Vector<Unicode::CalendarPattern> get_calendar_available_formats(StringView locale, StringView calendar);
  558. }
  559. }
  560. )~~~");
  561. VERIFY(file.write(generator.as_string_view()));
  562. }
  563. static void generate_unicode_locale_implementation(Core::File& file, UnicodeLocaleData& locale_data)
  564. {
  565. StringBuilder builder;
  566. SourceGenerator generator { builder };
  567. generator.set("string_index_type"sv, s_string_index_type);
  568. generator.set("calendar_pattern_index_type"sv, s_calendar_pattern_index_type);
  569. generator.append(R"~~~(
  570. #include <AK/Array.h>
  571. #include <AK/BinarySearch.h>
  572. #include <LibUnicode/DateTimeFormat.h>
  573. #include <LibUnicode/Locale.h>
  574. #include <LibUnicode/UnicodeDateTimeFormat.h>
  575. namespace Unicode::Detail {
  576. )~~~");
  577. locale_data.unique_strings.generate(generator);
  578. generator.append(R"~~~(
  579. struct CalendarPattern {
  580. Unicode::CalendarPattern to_unicode_calendar_pattern() const {
  581. Unicode::CalendarPattern calendar_pattern {};
  582. calendar_pattern.pattern = s_string_list[pattern];
  583. if (pattern12 != 0)
  584. calendar_pattern.pattern12 = s_string_list[pattern12];
  585. if (era != -1)
  586. calendar_pattern.era = static_cast<Unicode::CalendarPatternStyle>(era);
  587. if (year != -1)
  588. calendar_pattern.year = static_cast<Unicode::CalendarPatternStyle>(year);
  589. if (month != -1)
  590. calendar_pattern.month = static_cast<Unicode::CalendarPatternStyle>(month);
  591. if (weekday != -1)
  592. calendar_pattern.weekday = static_cast<Unicode::CalendarPatternStyle>(weekday);
  593. if (day != -1)
  594. calendar_pattern.day = static_cast<Unicode::CalendarPatternStyle>(day);
  595. if (day_period != -1)
  596. calendar_pattern.day_period = static_cast<Unicode::CalendarPatternStyle>(day_period);
  597. if (hour != -1)
  598. calendar_pattern.hour = static_cast<Unicode::CalendarPatternStyle>(hour);
  599. if (minute != -1)
  600. calendar_pattern.minute = static_cast<Unicode::CalendarPatternStyle>(minute);
  601. if (second != -1)
  602. calendar_pattern.second = static_cast<Unicode::CalendarPatternStyle>(second);
  603. if (fractional_second_digits != -1)
  604. calendar_pattern.fractional_second_digits = static_cast<u8>(fractional_second_digits);
  605. if (time_zone_name != -1)
  606. calendar_pattern.time_zone_name = static_cast<Unicode::CalendarPatternStyle>(time_zone_name);
  607. return calendar_pattern;
  608. }
  609. @string_index_type@ pattern { 0 };
  610. @string_index_type@ pattern12 { 0 };
  611. i8 era { -1 };
  612. i8 year { -1 };
  613. i8 month { -1 };
  614. i8 weekday { -1 };
  615. i8 day { -1 };
  616. i8 day_period { -1 };
  617. i8 hour { -1 };
  618. i8 minute { -1 };
  619. i8 second { -1 };
  620. i8 fractional_second_digits { -1 };
  621. i8 time_zone_name { -1 };
  622. };
  623. )~~~");
  624. locale_data.unique_patterns.generate(generator, "CalendarPattern"sv, "s_calendar_patterns"sv, 10);
  625. generator.append(R"~~~(
  626. struct CalendarFormat {
  627. Unicode::CalendarFormat to_unicode_calendar_format() const {
  628. Unicode::CalendarFormat calendar_format {};
  629. calendar_format.full_format = s_calendar_patterns[full_format].to_unicode_calendar_pattern();
  630. calendar_format.long_format = s_calendar_patterns[long_format].to_unicode_calendar_pattern();
  631. calendar_format.medium_format = s_calendar_patterns[medium_format].to_unicode_calendar_pattern();
  632. calendar_format.short_format = s_calendar_patterns[short_format].to_unicode_calendar_pattern();
  633. return calendar_format;
  634. }
  635. @calendar_pattern_index_type@ full_format { 0 };
  636. @calendar_pattern_index_type@ long_format { 0 };
  637. @calendar_pattern_index_type@ medium_format { 0 };
  638. @calendar_pattern_index_type@ short_format { 0 };
  639. };
  640. struct CalendarData {
  641. @string_index_type@ calendar { 0 };
  642. CalendarFormat date_formats {};
  643. CalendarFormat time_formats {};
  644. CalendarFormat date_time_formats {};
  645. Span<@calendar_pattern_index_type@ const> available_formats {};
  646. };
  647. )~~~");
  648. auto append_calendar_format = [&](auto const& calendar_format) {
  649. generator.set("full_format", String::number(calendar_format.full_format));
  650. generator.set("long_format", String::number(calendar_format.long_format));
  651. generator.set("medium_format", String::number(calendar_format.medium_format));
  652. generator.set("short_format", String::number(calendar_format.short_format));
  653. generator.append("{ @full_format@, @long_format@, @medium_format@, @short_format@ },");
  654. };
  655. auto append_calendars = [&](String name, auto const& calendars) {
  656. auto format_name = [&](StringView calendar_key) {
  657. return String::formatted("{}_{}_formats", name, calendar_key);
  658. };
  659. for (auto const& calendar_key : locale_data.calendars) {
  660. auto const& calendar = calendars.find(calendar_key)->value;
  661. generator.set("name", format_name(calendar_key));
  662. generator.set("size", String::number(calendar.available_formats.size()));
  663. generator.append(R"~~~(
  664. static constexpr Array<@calendar_pattern_index_type@, @size@> @name@ { {)~~~");
  665. bool first = true;
  666. for (auto format : calendar.available_formats) {
  667. generator.append(first ? " " : ", ");
  668. generator.append(String::number(format));
  669. first = false;
  670. }
  671. generator.append(" } };");
  672. }
  673. generator.set("name", name);
  674. generator.set("size", String::number(calendars.size()));
  675. generator.append(R"~~~(
  676. static constexpr Array<CalendarData, @size@> @name@ { {)~~~");
  677. for (auto const& calendar_key : locale_data.calendars) {
  678. auto const& calendar = calendars.find(calendar_key)->value;
  679. generator.set("name", format_name(calendar_key));
  680. generator.set("calendar"sv, String::number(calendar.calendar));
  681. generator.append(R"~~~(
  682. { @calendar@, )~~~");
  683. append_calendar_format(calendar.date_formats);
  684. generator.append(" ");
  685. append_calendar_format(calendar.time_formats);
  686. generator.append(" ");
  687. append_calendar_format(calendar.date_time_formats);
  688. generator.append(" @name@.span() },");
  689. }
  690. generator.append(R"~~~(
  691. } };
  692. )~~~");
  693. };
  694. auto append_hour_cycles = [&](String name, auto const& hour_cycle_region) {
  695. auto const& hour_cycles = locale_data.hour_cycles.find(hour_cycle_region)->value;
  696. generator.set("name", name);
  697. generator.set("size", String::number(hour_cycles.size()));
  698. generator.append(R"~~~(
  699. static constexpr Array<u8, @size@> @name@ { { )~~~");
  700. for (auto hour_cycle : hour_cycles) {
  701. generator.set("hour_cycle", String::number(static_cast<u8>(hour_cycle)));
  702. generator.append("@hour_cycle@, ");
  703. }
  704. generator.append("} };");
  705. };
  706. generate_mapping(generator, locale_data.locales, "CalendarData"sv, "s_calendars"sv, "s_calendars_{}", [&](auto const& name, auto const& value) { append_calendars(name, value.calendars); });
  707. generate_mapping(generator, locale_data.hour_cycle_regions, "u8"sv, "s_hour_cycles"sv, "s_hour_cycles_{}", [&](auto const& name, auto const& value) { append_hour_cycles(name, value); });
  708. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) {
  709. HashValueMap<String> hashes;
  710. hashes.ensure_capacity(values.size());
  711. for (auto const& value : values)
  712. hashes.set(value.hash(), format_identifier(enum_title, value));
  713. for (auto const& alias : aliases)
  714. hashes.set(alias.alias.hash(), format_identifier(enum_title, alias.alias));
  715. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  716. };
  717. append_from_string("Calendar"sv, "calendar"sv, locale_data.calendars, locale_data.calendar_aliases);
  718. append_from_string("HourCycleRegion"sv, "hour_cycle_region"sv, locale_data.hour_cycle_regions);
  719. generator.append(R"~~~(
  720. Vector<Unicode::HourCycle> get_regional_hour_cycles(StringView region)
  721. {
  722. auto region_value = hour_cycle_region_from_string(region);
  723. if (!region_value.has_value())
  724. return {};
  725. auto region_index = to_underlying(*region_value);
  726. auto const& regional_hour_cycles = s_hour_cycles.at(region_index);
  727. Vector<Unicode::HourCycle> hour_cycles;
  728. hour_cycles.ensure_capacity(regional_hour_cycles.size());
  729. for (auto hour_cycle : regional_hour_cycles)
  730. hour_cycles.unchecked_append(static_cast<Unicode::HourCycle>(hour_cycle));
  731. return hour_cycles;
  732. }
  733. static CalendarData const* find_calendar_data(StringView locale, StringView calendar)
  734. {
  735. auto locale_value = locale_from_string(locale);
  736. if (!locale_value.has_value())
  737. return nullptr;
  738. auto calendar_value = calendar_from_string(calendar);
  739. if (!calendar_value.has_value())
  740. return nullptr;
  741. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  742. auto calendar_index = to_underlying(*calendar_value);
  743. auto const& calendars = s_calendars.at(locale_index);
  744. return &calendars[calendar_index];
  745. }
  746. Optional<Unicode::CalendarFormat> get_calendar_date_format(StringView locale, StringView calendar)
  747. {
  748. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  749. return data->date_formats.to_unicode_calendar_format();
  750. return {};
  751. }
  752. Optional<Unicode::CalendarFormat> get_calendar_time_format(StringView locale, StringView calendar)
  753. {
  754. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  755. return data->time_formats.to_unicode_calendar_format();
  756. return {};
  757. }
  758. Optional<Unicode::CalendarFormat> get_calendar_date_time_format(StringView locale, StringView calendar)
  759. {
  760. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  761. return data->date_time_formats.to_unicode_calendar_format();
  762. return {};
  763. }
  764. Vector<Unicode::CalendarPattern> get_calendar_available_formats(StringView locale, StringView calendar)
  765. {
  766. Vector<Unicode::CalendarPattern> result {};
  767. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  768. result.ensure_capacity(data->available_formats.size());
  769. for (auto const& format : data->available_formats)
  770. result.unchecked_append(s_calendar_patterns[format].to_unicode_calendar_pattern());
  771. }
  772. return result;
  773. }
  774. }
  775. )~~~");
  776. VERIFY(file.write(generator.as_string_view()));
  777. }
  778. ErrorOr<int> serenity_main(Main::Arguments arguments)
  779. {
  780. StringView generated_header_path;
  781. StringView generated_implementation_path;
  782. StringView core_path;
  783. StringView dates_path;
  784. Core::ArgsParser args_parser;
  785. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  786. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  787. args_parser.add_option(core_path, "Path to cldr-core directory", "core-path", 'r', "core-path");
  788. args_parser.add_option(dates_path, "Path to cldr-dates directory", "dates-path", 'd', "dates-path");
  789. args_parser.parse(arguments);
  790. auto open_file = [&](StringView path) -> ErrorOr<NonnullRefPtr<Core::File>> {
  791. if (path.is_empty()) {
  792. args_parser.print_usage(stderr, arguments.argv[0]);
  793. return Error::from_string_literal("Must provide all command line options"sv);
  794. }
  795. return Core::File::open(path, Core::OpenMode::ReadWrite);
  796. };
  797. auto generated_header_file = TRY(open_file(generated_header_path));
  798. auto generated_implementation_file = TRY(open_file(generated_implementation_path));
  799. UnicodeLocaleData locale_data;
  800. TRY(parse_all_locales(core_path, dates_path, locale_data));
  801. generate_unicode_locale_header(generated_header_file, locale_data);
  802. generate_unicode_locale_implementation(generated_implementation_file, locale_data);
  803. return 0;
  804. }