GenerateUnicodeDateTimeFormat.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  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. using CalendarRangePatternIndexType = u16;
  31. constexpr auto s_calendar_range_pattern_index_type = "u16"sv;
  32. struct CalendarPattern : public Unicode::CalendarPattern {
  33. bool contains_only_date_fields() const
  34. {
  35. return !day_period.has_value() && !hour.has_value() && !minute.has_value() && !second.has_value() && !fractional_second_digits.has_value() && !time_zone_name.has_value();
  36. }
  37. bool contains_only_time_fields() const
  38. {
  39. return !weekday.has_value() && !era.has_value() && !year.has_value() && !month.has_value() && !day.has_value();
  40. }
  41. unsigned hash() const
  42. {
  43. auto hash = pair_int_hash(pattern_index, pattern12_index);
  44. hash = pair_int_hash(hash, skeleton_index);
  45. auto hash_field = [&](auto const& field) {
  46. if (field.has_value())
  47. hash = pair_int_hash(hash, static_cast<u8>(*field));
  48. else
  49. hash = pair_int_hash(hash, -1);
  50. };
  51. hash_field(era);
  52. hash_field(year);
  53. hash_field(month);
  54. hash_field(weekday);
  55. hash_field(day);
  56. hash_field(day_period);
  57. hash_field(hour);
  58. hash_field(minute);
  59. hash_field(second);
  60. hash_field(fractional_second_digits);
  61. hash_field(time_zone_name);
  62. return hash;
  63. }
  64. bool operator==(CalendarPattern const& other) const
  65. {
  66. return (skeleton_index == other.skeleton_index)
  67. && (pattern_index == other.pattern_index)
  68. && (pattern12_index == other.pattern12_index)
  69. && (era == other.era)
  70. && (year == other.year)
  71. && (month == other.month)
  72. && (weekday == other.weekday)
  73. && (day == other.day)
  74. && (day_period == other.day_period)
  75. && (hour == other.hour)
  76. && (minute == other.minute)
  77. && (second == other.second)
  78. && (fractional_second_digits == other.fractional_second_digits)
  79. && (time_zone_name == other.time_zone_name);
  80. }
  81. StringIndexType skeleton_index { 0 };
  82. StringIndexType pattern_index { 0 };
  83. StringIndexType pattern12_index { 0 };
  84. };
  85. template<>
  86. struct AK::Formatter<CalendarPattern> : Formatter<FormatString> {
  87. ErrorOr<void> format(FormatBuilder& builder, CalendarPattern const& pattern)
  88. {
  89. auto field_to_i8 = [](auto const& field) -> i8 {
  90. if (!field.has_value())
  91. return -1;
  92. return static_cast<i8>(*field);
  93. };
  94. return Formatter<FormatString>::format(builder,
  95. "{{ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} }}",
  96. pattern.skeleton_index,
  97. pattern.pattern_index,
  98. pattern.pattern12_index,
  99. field_to_i8(pattern.era),
  100. field_to_i8(pattern.year),
  101. field_to_i8(pattern.month),
  102. field_to_i8(pattern.weekday),
  103. field_to_i8(pattern.day),
  104. field_to_i8(pattern.day_period),
  105. field_to_i8(pattern.hour),
  106. field_to_i8(pattern.minute),
  107. field_to_i8(pattern.second),
  108. field_to_i8(pattern.fractional_second_digits),
  109. field_to_i8(pattern.time_zone_name));
  110. }
  111. };
  112. template<>
  113. struct AK::Traits<CalendarPattern> : public GenericTraits<CalendarPattern> {
  114. static unsigned hash(CalendarPattern const& c) { return c.hash(); }
  115. };
  116. struct CalendarRangePattern : public CalendarPattern {
  117. unsigned hash() const
  118. {
  119. auto hash = CalendarPattern::hash();
  120. if (field.has_value())
  121. hash = pair_int_hash(hash, static_cast<u8>(*field));
  122. hash = pair_int_hash(hash, start_range);
  123. hash = pair_int_hash(hash, separator);
  124. hash = pair_int_hash(hash, end_range);
  125. return hash;
  126. }
  127. bool operator==(CalendarRangePattern const& other) const
  128. {
  129. if (!CalendarPattern::operator==(other))
  130. return false;
  131. return (field == other.field)
  132. && (start_range == other.start_range)
  133. && (separator == other.separator)
  134. && (end_range == other.end_range);
  135. }
  136. Optional<Unicode::CalendarRangePattern::Field> field {};
  137. StringIndexType start_range { 0 };
  138. StringIndexType separator { 0 };
  139. StringIndexType end_range { 0 };
  140. };
  141. template<>
  142. struct AK::Formatter<CalendarRangePattern> : Formatter<FormatString> {
  143. ErrorOr<void> format(FormatBuilder& builder, CalendarRangePattern const& pattern)
  144. {
  145. auto field_to_i8 = [](auto const& field) -> i8 {
  146. if (!field.has_value())
  147. return -1;
  148. return static_cast<i8>(*field);
  149. };
  150. return Formatter<FormatString>::format(builder,
  151. "{{ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} }}",
  152. pattern.skeleton_index,
  153. field_to_i8(pattern.field),
  154. pattern.start_range,
  155. pattern.separator,
  156. pattern.end_range,
  157. field_to_i8(pattern.era),
  158. field_to_i8(pattern.year),
  159. field_to_i8(pattern.month),
  160. field_to_i8(pattern.weekday),
  161. field_to_i8(pattern.day),
  162. field_to_i8(pattern.day_period),
  163. field_to_i8(pattern.hour),
  164. field_to_i8(pattern.minute),
  165. field_to_i8(pattern.second),
  166. field_to_i8(pattern.fractional_second_digits),
  167. field_to_i8(pattern.time_zone_name));
  168. }
  169. };
  170. template<>
  171. struct AK::Traits<CalendarRangePattern> : public GenericTraits<CalendarRangePattern> {
  172. static unsigned hash(CalendarRangePattern const& c) { return c.hash(); }
  173. };
  174. struct CalendarFormat {
  175. CalendarPatternIndexType full_format { 0 };
  176. CalendarPatternIndexType long_format { 0 };
  177. CalendarPatternIndexType medium_format { 0 };
  178. CalendarPatternIndexType short_format { 0 };
  179. };
  180. struct CalendarSymbols {
  181. Vector<StringIndexType> narrow_symbols {};
  182. Vector<StringIndexType> short_symbols {};
  183. Vector<StringIndexType> long_symbols {};
  184. };
  185. struct Calendar {
  186. StringIndexType calendar { 0 };
  187. CalendarFormat date_formats {};
  188. CalendarFormat time_formats {};
  189. CalendarFormat date_time_formats {};
  190. Vector<CalendarPatternIndexType> available_formats {};
  191. CalendarRangePatternIndexType default_range_format { 0 };
  192. Vector<CalendarRangePatternIndexType> range_formats {};
  193. Vector<CalendarRangePatternIndexType> range12_formats {};
  194. HashMap<String, CalendarSymbols> symbols {};
  195. };
  196. struct TimeZone {
  197. StringIndexType time_zone { 0 };
  198. StringIndexType long_name { 0 };
  199. StringIndexType short_name { 0 };
  200. };
  201. struct DayPeriod {
  202. Unicode::DayPeriod day_period {};
  203. u8 begin { 0 };
  204. u8 end { 0 };
  205. };
  206. struct Locale {
  207. HashMap<String, Calendar> calendars;
  208. HashMap<String, TimeZone> time_zones;
  209. Vector<DayPeriod> day_periods;
  210. };
  211. struct UnicodeLocaleData {
  212. UniqueStringStorage<StringIndexType> unique_strings;
  213. UniqueStorage<CalendarPattern, CalendarPatternIndexType> unique_patterns;
  214. UniqueStorage<CalendarRangePattern, CalendarRangePatternIndexType> unique_range_patterns;
  215. HashMap<String, Locale> locales;
  216. HashMap<String, Vector<Unicode::HourCycle>> hour_cycles;
  217. Vector<String> hour_cycle_regions;
  218. HashMap<String, StringIndexType> meta_zones;
  219. Vector<String> time_zones;
  220. Vector<String> calendars;
  221. Vector<Alias> calendar_aliases {
  222. // FIXME: Aliases should come from BCP47. See: https://unicode-org.atlassian.net/browse/CLDR-15158
  223. { "gregorian"sv, "gregory"sv },
  224. };
  225. Vector<String> symbols;
  226. };
  227. static Optional<Unicode::DayPeriod> day_period_from_string(StringView day_period)
  228. {
  229. if (day_period == "am"sv)
  230. return Unicode::DayPeriod::AM;
  231. if (day_period == "pm"sv)
  232. return Unicode::DayPeriod::PM;
  233. if (day_period == "morning1"sv)
  234. return Unicode::DayPeriod::Morning1;
  235. if (day_period == "morning2"sv)
  236. return Unicode::DayPeriod::Morning2;
  237. if (day_period == "afternoon1"sv)
  238. return Unicode::DayPeriod::Afternoon1;
  239. if (day_period == "afternoon2"sv)
  240. return Unicode::DayPeriod::Afternoon2;
  241. if (day_period == "evening1"sv)
  242. return Unicode::DayPeriod::Evening1;
  243. if (day_period == "evening2"sv)
  244. return Unicode::DayPeriod::Evening2;
  245. if (day_period == "night1"sv)
  246. return Unicode::DayPeriod::Night1;
  247. if (day_period == "night2"sv)
  248. return Unicode::DayPeriod::Night2;
  249. return {};
  250. };
  251. static ErrorOr<void> parse_hour_cycles(String core_path, UnicodeLocaleData& locale_data)
  252. {
  253. // https://unicode.org/reports/tr35/tr35-dates.html#Time_Data
  254. LexicalPath time_data_path(move(core_path));
  255. time_data_path = time_data_path.append("supplemental"sv);
  256. time_data_path = time_data_path.append("timeData.json"sv);
  257. auto time_data_file = TRY(Core::File::open(time_data_path.string(), Core::OpenMode::ReadOnly));
  258. auto time_data = TRY(JsonValue::from_string(time_data_file->read_all()));
  259. auto const& supplemental_object = time_data.as_object().get("supplemental"sv);
  260. auto const& time_data_object = supplemental_object.as_object().get("timeData"sv);
  261. auto parse_hour_cycle = [](StringView hour_cycle) -> Optional<Unicode::HourCycle> {
  262. if (hour_cycle == "h"sv)
  263. return Unicode::HourCycle::H12;
  264. if (hour_cycle == "H"sv)
  265. return Unicode::HourCycle::H23;
  266. if (hour_cycle == "K"sv)
  267. return Unicode::HourCycle::H11;
  268. if (hour_cycle == "k"sv)
  269. return Unicode::HourCycle::H24;
  270. return {};
  271. };
  272. time_data_object.as_object().for_each_member([&](auto const& key, JsonValue const& value) {
  273. auto allowed_hour_cycles_string = value.as_object().get("_allowed"sv).as_string();
  274. auto allowed_hour_cycles = allowed_hour_cycles_string.split_view(' ');
  275. Vector<Unicode::HourCycle> hour_cycles;
  276. for (auto allowed_hour_cycle : allowed_hour_cycles) {
  277. if (auto hour_cycle = parse_hour_cycle(allowed_hour_cycle); hour_cycle.has_value())
  278. hour_cycles.append(*hour_cycle);
  279. }
  280. locale_data.hour_cycles.set(key, move(hour_cycles));
  281. if (!locale_data.hour_cycle_regions.contains_slow(key))
  282. locale_data.hour_cycle_regions.append(key);
  283. });
  284. return {};
  285. };
  286. static ErrorOr<void> parse_meta_zones(String core_path, UnicodeLocaleData& locale_data)
  287. {
  288. // https://unicode.org/reports/tr35/tr35-dates.html#Metazones
  289. LexicalPath meta_zone_path(move(core_path));
  290. meta_zone_path = meta_zone_path.append("supplemental"sv);
  291. meta_zone_path = meta_zone_path.append("metaZones.json"sv);
  292. auto meta_zone_file = TRY(Core::File::open(meta_zone_path.string(), Core::OpenMode::ReadOnly));
  293. auto meta_zone = TRY(JsonValue::from_string(meta_zone_file->read_all()));
  294. auto const& supplemental_object = meta_zone.as_object().get("supplemental"sv);
  295. auto const& meta_zone_object = supplemental_object.as_object().get("metaZones"sv);
  296. auto const& meta_zone_array = meta_zone_object.as_object().get("metazones"sv);
  297. meta_zone_array.as_array().for_each([&](JsonValue const& value) {
  298. auto const& mapping = value.as_object().get("mapZone"sv);
  299. auto const& meta_zone = mapping.as_object().get("_other"sv);
  300. auto const& golden_zone = mapping.as_object().get("_type"sv);
  301. auto golden_zone_index = locale_data.unique_strings.ensure(golden_zone.as_string());
  302. locale_data.meta_zones.set(meta_zone.as_string(), golden_zone_index);
  303. });
  304. // UTC does not appear in metaZones.json. Define it for convenience so other parsers don't need to check for its existence.
  305. locale_data.meta_zones.set("UTC"sv, locale_data.unique_strings.ensure("UTC"sv));
  306. return {};
  307. };
  308. static constexpr auto is_char(char ch)
  309. {
  310. return [ch](auto c) { return c == ch; };
  311. }
  312. // For patterns that are 12-hour aware, we need to generate two patterns: one with the day period
  313. // (e.g. {ampm}) in the pattern, and one without the day period. We need to take care to remove
  314. // extra spaces around the day period. Some example expected removals:
  315. //
  316. // "{hour}:{minute} {ampm}" becomes "{hour}:{minute}" (remove the space before {ampm})
  317. // "{ampm} {hour}" becomes "{hour}" (remove the space after {ampm})
  318. // "{hour}:{minute} {ampm} {timeZoneName}" becomes "{hour}:{minute} {timeZoneName}" (remove one of the spaces around {ampm})
  319. static String remove_period_from_pattern(String pattern)
  320. {
  321. for (auto remove : AK::Array { "({ampm})"sv, "{ampm}"sv, "({dayPeriod})"sv, "{dayPeriod}"sv }) {
  322. auto index = pattern.find(remove);
  323. if (!index.has_value())
  324. continue;
  325. constexpr u32 space = ' ';
  326. constexpr u32 open = '{';
  327. constexpr u32 close = '}';
  328. Utf8View utf8_pattern { pattern };
  329. Optional<u32> before_removal;
  330. Optional<u32> after_removal;
  331. for (auto it = utf8_pattern.begin(); utf8_pattern.byte_offset_of(it) < *index; ++it)
  332. before_removal = *it;
  333. if (auto it = utf8_pattern.iterator_at_byte_offset(*index + remove.length()); it != utf8_pattern.end())
  334. after_removal = *it;
  335. if ((before_removal == space) && (after_removal != open)) {
  336. pattern = String::formatted("{}{}",
  337. pattern.substring_view(0, *index - 1),
  338. pattern.substring_view(*index + remove.length()));
  339. } else if ((after_removal == space) && (before_removal != close)) {
  340. pattern = String::formatted("{}{}",
  341. pattern.substring_view(0, *index),
  342. pattern.substring_view(*index + remove.length() + 1));
  343. } else {
  344. pattern = String::formatted("{}{}",
  345. pattern.substring_view(0, *index),
  346. pattern.substring_view(*index + remove.length()));
  347. }
  348. }
  349. return pattern;
  350. }
  351. static Optional<CalendarPattern> parse_date_time_pattern_raw(String pattern, String skeleton, UnicodeLocaleData& locale_data)
  352. {
  353. // https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
  354. using Unicode::CalendarPatternStyle;
  355. CalendarPattern format {};
  356. if (!skeleton.is_empty())
  357. format.skeleton_index = locale_data.unique_strings.ensure(move(skeleton));
  358. GenericLexer lexer { pattern };
  359. StringBuilder builder;
  360. bool hour12 { false };
  361. while (!lexer.is_eof()) {
  362. // Literal strings enclosed by quotes are to be appended to the pattern as-is without further
  363. // processing (this just avoids conflicts with the patterns below).
  364. if (lexer.next_is(is_quote)) {
  365. builder.append(lexer.consume_quoted_string());
  366. continue;
  367. }
  368. auto starting_char = lexer.peek();
  369. auto segment = lexer.consume_while([&](char ch) { return ch == starting_char; });
  370. // Era
  371. if (all_of(segment, is_char('G'))) {
  372. builder.append("{era}");
  373. if (segment.length() <= 3)
  374. format.era = CalendarPatternStyle::Short;
  375. else if (segment.length() == 4)
  376. format.era = CalendarPatternStyle::Long;
  377. else
  378. format.era = CalendarPatternStyle::Narrow;
  379. }
  380. // Year
  381. else if (all_of(segment, is_any_of("yYuUr"sv))) {
  382. builder.append("{year}");
  383. if (segment.length() == 2)
  384. format.year = CalendarPatternStyle::TwoDigit;
  385. else
  386. format.year = CalendarPatternStyle::Numeric;
  387. }
  388. // Quarter
  389. else if (all_of(segment, is_any_of("qQ"sv))) {
  390. // Intl.DateTimeFormat does not support quarter formatting, so drop these patterns.
  391. return {};
  392. }
  393. // Month
  394. else if (all_of(segment, is_any_of("ML"sv))) {
  395. builder.append("{month}");
  396. if (segment.length() == 1)
  397. format.month = CalendarPatternStyle::Numeric;
  398. else if (segment.length() == 2)
  399. format.month = CalendarPatternStyle::TwoDigit;
  400. else if (segment.length() == 3)
  401. format.month = CalendarPatternStyle::Short;
  402. else if (segment.length() == 4)
  403. format.month = CalendarPatternStyle::Long;
  404. else if (segment.length() == 5)
  405. format.month = CalendarPatternStyle::Narrow;
  406. } else if (all_of(segment, is_char('l'))) {
  407. // Using 'l' for month formatting is deprecated by TR-35, ensure it is not used.
  408. return {};
  409. }
  410. // Week
  411. else if (all_of(segment, is_any_of("wW"sv))) {
  412. // Intl.DateTimeFormat does not support week formatting, so drop these patterns.
  413. return {};
  414. }
  415. // Day
  416. else if (all_of(segment, is_char('d'))) {
  417. builder.append("{day}");
  418. if (segment.length() == 1)
  419. format.day = CalendarPatternStyle::Numeric;
  420. else
  421. format.day = CalendarPatternStyle::TwoDigit;
  422. } else if (all_of(segment, is_any_of("DFg"sv))) {
  423. builder.append("{day}");
  424. format.day = CalendarPatternStyle::Numeric;
  425. }
  426. // Weekday
  427. else if (all_of(segment, is_char('E'))) {
  428. builder.append("{weekday}");
  429. if (segment.length() == 4)
  430. format.weekday = CalendarPatternStyle::Long;
  431. else if (segment.length() == 5)
  432. format.weekday = CalendarPatternStyle::Narrow;
  433. else
  434. format.weekday = CalendarPatternStyle::Short;
  435. } else if (all_of(segment, is_any_of("ec"sv))) {
  436. builder.append("{weekday}");
  437. // TR-35 defines "e", "c", and "cc" as as numeric, and "ee" as 2-digit, but those
  438. // pattern styles are not supported by Intl.DateTimeFormat.
  439. if (segment.length() <= 2)
  440. return {};
  441. if (segment.length() == 4)
  442. format.weekday = CalendarPatternStyle::Long;
  443. else if (segment.length() == 5)
  444. format.weekday = CalendarPatternStyle::Narrow;
  445. else
  446. format.weekday = CalendarPatternStyle::Short;
  447. }
  448. // Period
  449. else if (all_of(segment, is_any_of("ab"sv))) {
  450. builder.append("{ampm}");
  451. hour12 = true;
  452. } else if (all_of(segment, is_char('B'))) {
  453. builder.append("{dayPeriod}");
  454. hour12 = true;
  455. if (segment.length() == 4)
  456. format.day_period = CalendarPatternStyle::Long;
  457. else if (segment.length() == 5)
  458. format.day_period = CalendarPatternStyle::Narrow;
  459. else
  460. format.day_period = CalendarPatternStyle::Short;
  461. }
  462. // Hour
  463. else if (all_of(segment, is_any_of("hHKk"sv))) {
  464. builder.append("{hour}");
  465. if ((segment[0] == 'h') || (segment[0] == 'K'))
  466. hour12 = true;
  467. if (segment.length() == 1)
  468. format.hour = CalendarPatternStyle::Numeric;
  469. else
  470. format.hour = CalendarPatternStyle::TwoDigit;
  471. } else if (all_of(segment, is_any_of("jJC"sv))) {
  472. // TR-35 indicates these should not be used.
  473. return {};
  474. }
  475. // Minute
  476. else if (all_of(segment, is_char('m'))) {
  477. builder.append("{minute}");
  478. if (segment.length() == 1)
  479. format.minute = CalendarPatternStyle::Numeric;
  480. else
  481. format.minute = CalendarPatternStyle::TwoDigit;
  482. }
  483. // Second
  484. else if (all_of(segment, is_char('s'))) {
  485. builder.append("{second}");
  486. if (segment.length() == 1)
  487. format.second = CalendarPatternStyle::Numeric;
  488. else
  489. format.second = CalendarPatternStyle::TwoDigit;
  490. } else if (all_of(segment, is_char('S'))) {
  491. builder.append("{fractionalSecondDigits}");
  492. VERIFY(segment.length() <= 3);
  493. format.fractional_second_digits = static_cast<u8>(segment.length());
  494. } else if (all_of(segment, is_char('A'))) {
  495. // Intl.DateTimeFormat does not support millisecond formatting, so drop these patterns.
  496. return {};
  497. }
  498. // Zone
  499. else if (all_of(segment, is_any_of("zZOvVXx"))) {
  500. builder.append("{timeZoneName}");
  501. if (segment.length() < 4)
  502. format.time_zone_name = CalendarPatternStyle::Short;
  503. else
  504. format.time_zone_name = CalendarPatternStyle::Long;
  505. }
  506. // Non-patterns
  507. else {
  508. builder.append(segment);
  509. }
  510. }
  511. pattern = builder.build();
  512. if (hour12) {
  513. format.pattern = remove_period_from_pattern(pattern);
  514. format.pattern12 = move(pattern);
  515. } else {
  516. format.pattern = move(pattern);
  517. }
  518. return format;
  519. }
  520. static Optional<CalendarPatternIndexType> parse_date_time_pattern(String pattern, String skeleton, UnicodeLocaleData& locale_data)
  521. {
  522. auto format = parse_date_time_pattern_raw(move(pattern), move(skeleton), locale_data);
  523. if (!format.has_value())
  524. return {};
  525. format->pattern_index = locale_data.unique_strings.ensure(move(format->pattern));
  526. if (format->pattern12.has_value())
  527. format->pattern12_index = locale_data.unique_strings.ensure(format->pattern12.release_value());
  528. return locale_data.unique_patterns.ensure(format.release_value());
  529. }
  530. template<typename... Chars>
  531. static constexpr bool char_is_one_of(char ch, Chars&&... chars)
  532. {
  533. return ((ch == chars) || ...);
  534. }
  535. static void parse_interval_patterns(Calendar& calendar, JsonObject const& interval_formats_object, UnicodeLocaleData& locale_data)
  536. {
  537. // https://unicode.org/reports/tr35/tr35-dates.html#intervalFormats
  538. auto name_of_field = [&](char field) {
  539. if (char_is_one_of(field, 'G'))
  540. return Unicode::CalendarRangePattern::Field::Era;
  541. if (char_is_one_of(field, 'y', 'Y', 'u', 'U', 'r'))
  542. return Unicode::CalendarRangePattern::Field::Year;
  543. if (char_is_one_of(field, 'M', 'L'))
  544. return Unicode::CalendarRangePattern::Field::Month;
  545. if (char_is_one_of(field, 'd', 'D', 'F', 'g'))
  546. return Unicode::CalendarRangePattern::Field::Day;
  547. if (char_is_one_of(field, 'a', 'b'))
  548. return Unicode::CalendarRangePattern::Field::AmPm;
  549. if (char_is_one_of(field, 'B'))
  550. return Unicode::CalendarRangePattern::Field::DayPeriod;
  551. if (char_is_one_of(field, 'h', 'H', 'K', 'k'))
  552. return Unicode::CalendarRangePattern::Field::Hour;
  553. if (char_is_one_of(field, 'm'))
  554. return Unicode::CalendarRangePattern::Field::Minute;
  555. if (char_is_one_of(field, 's'))
  556. return Unicode::CalendarRangePattern::Field::Second;
  557. if (char_is_one_of(field, 'S'))
  558. return Unicode::CalendarRangePattern::Field::FractionalSecondDigits;
  559. VERIFY_NOT_REACHED();
  560. };
  561. auto split_default_range_pattern = [&](auto skeleton, auto const& pattern) {
  562. auto start_range_end = pattern.find('}').value() + 1;
  563. auto end_range_begin = pattern.find_last('{').value();
  564. auto start_range = pattern.substring_view(0, start_range_end);
  565. auto separator = pattern.substring_view(start_range_end, end_range_begin - start_range_end);
  566. auto end_range = pattern.substring_view(end_range_begin);
  567. CalendarRangePattern format {};
  568. format.skeleton_index = locale_data.unique_strings.ensure(skeleton);
  569. format.start_range = locale_data.unique_strings.ensure(start_range);
  570. format.separator = locale_data.unique_strings.ensure(separator);
  571. format.end_range = locale_data.unique_strings.ensure(end_range);
  572. return format;
  573. };
  574. auto split_range_pattern = [&](auto skeleton, auto field, auto const& pattern, auto const& parsed_fields) {
  575. HashMap<StringView, size_t> partitions;
  576. StringView last_partition;
  577. auto begin_index = pattern.find('{');
  578. size_t end_index = 0;
  579. while (begin_index.has_value()) {
  580. end_index = pattern.find('}', *begin_index).value();
  581. auto partition = pattern.substring_view(*begin_index, end_index - *begin_index);
  582. if (partitions.contains(partition))
  583. break;
  584. partitions.set(partition, *begin_index);
  585. last_partition = partition;
  586. begin_index = pattern.find('{', end_index + 1);
  587. }
  588. VERIFY(begin_index.has_value() && !last_partition.is_empty());
  589. auto start_range_end = partitions.get(last_partition).value() + last_partition.length() + 1;
  590. auto start_range = pattern.substring_view(0, start_range_end);
  591. auto separator = pattern.substring_view(start_range_end, *begin_index - start_range_end);
  592. auto end_range = pattern.substring_view(*begin_index);
  593. CalendarRangePattern format {};
  594. format.skeleton_index = locale_data.unique_strings.ensure(skeleton);
  595. format.field = field;
  596. format.start_range = locale_data.unique_strings.ensure(start_range);
  597. format.separator = locale_data.unique_strings.ensure(separator);
  598. format.end_range = locale_data.unique_strings.ensure(end_range);
  599. format.for_each_calendar_field_zipped_with(parsed_fields, [](auto& format_field, auto const& parsed_field, auto) {
  600. format_field = parsed_field;
  601. });
  602. return format;
  603. };
  604. interval_formats_object.for_each_member([&](auto const& skeleton, auto const& value) {
  605. if (skeleton == "intervalFormatFallback"sv) {
  606. auto range_format = split_default_range_pattern(skeleton, value.as_string());
  607. calendar.default_range_format = locale_data.unique_range_patterns.ensure(move(range_format));
  608. return;
  609. }
  610. value.as_object().for_each_member([&](auto const& field, auto const& pattern) {
  611. if (field.ends_with("alt-variant"sv))
  612. return;
  613. VERIFY(field.length() == 1);
  614. auto name = name_of_field(field[0]);
  615. auto format = parse_date_time_pattern_raw(pattern.as_string(), skeleton, locale_data).release_value();
  616. auto range_format = split_range_pattern(skeleton, name, format.pattern, format);
  617. calendar.range_formats.append(locale_data.unique_range_patterns.ensure(move(range_format)));
  618. if (format.pattern12.has_value()) {
  619. auto range12_pattern = split_range_pattern(skeleton, name, *format.pattern12, format);
  620. calendar.range12_formats.append(locale_data.unique_range_patterns.ensure(move(range12_pattern)));
  621. } else {
  622. calendar.range12_formats.append(calendar.range_formats.last());
  623. }
  624. });
  625. });
  626. }
  627. static void generate_missing_patterns(Calendar& calendar, Vector<CalendarPattern> date_formats, Vector<CalendarPattern> time_formats, UnicodeLocaleData& locale_data)
  628. {
  629. // https://unicode.org/reports/tr35/tr35-dates.html#Missing_Skeleton_Fields
  630. auto replace_pattern = [&](auto format, auto time_format, auto date_format) {
  631. auto pattern = locale_data.unique_strings.get(format);
  632. auto time_pattern = locale_data.unique_strings.get(time_format);
  633. auto date_pattern = locale_data.unique_strings.get(date_format);
  634. auto new_pattern = pattern.replace("{0}", time_pattern).replace("{1}", date_pattern);
  635. return locale_data.unique_strings.ensure(move(new_pattern));
  636. };
  637. auto inject_fractional_second_digits = [&](auto format) {
  638. auto pattern = locale_data.unique_strings.get(format);
  639. auto new_pattern = pattern.replace("{second}"sv, "{second}{decimal}{fractionalSecondDigits}"sv);
  640. return locale_data.unique_strings.ensure(move(new_pattern));
  641. };
  642. auto append_if_unique = [&](auto format) {
  643. auto format_index = locale_data.unique_patterns.ensure(move(format));
  644. if (!calendar.available_formats.contains_slow(format_index))
  645. calendar.available_formats.append(format_index);
  646. };
  647. Vector<CalendarPattern> time_formats_with_fractional_second_digits;
  648. for (auto const& format : date_formats)
  649. append_if_unique(format);
  650. for (auto const& format : time_formats) {
  651. append_if_unique(format);
  652. if (format.second.has_value() && !format.fractional_second_digits.has_value()) {
  653. auto new_format = format;
  654. new_format.fractional_second_digits = 2;
  655. new_format.pattern_index = inject_fractional_second_digits(new_format.pattern_index);
  656. if (new_format.pattern12_index != 0)
  657. new_format.pattern12_index = inject_fractional_second_digits(new_format.pattern12_index);
  658. time_formats_with_fractional_second_digits.append(new_format);
  659. append_if_unique(move(new_format));
  660. }
  661. }
  662. time_formats.extend(move(time_formats_with_fractional_second_digits));
  663. for (auto const& date_format : date_formats) {
  664. CalendarPatternIndexType date_time_format_index = 0;
  665. if (date_format.month == Unicode::CalendarPatternStyle::Long) {
  666. if (date_format.weekday.has_value())
  667. date_time_format_index = calendar.date_time_formats.full_format;
  668. else
  669. date_time_format_index = calendar.date_time_formats.long_format;
  670. } else if (date_format.month == Unicode::CalendarPatternStyle::Short) {
  671. date_time_format_index = calendar.date_time_formats.medium_format;
  672. } else {
  673. date_time_format_index = calendar.date_time_formats.short_format;
  674. }
  675. for (auto const& time_format : time_formats) {
  676. auto format = locale_data.unique_patterns.get(date_time_format_index);
  677. if (time_format.pattern12_index != 0)
  678. format.pattern12_index = replace_pattern(format.pattern_index, time_format.pattern12_index, date_format.pattern_index);
  679. format.pattern_index = replace_pattern(format.pattern_index, time_format.pattern_index, date_format.pattern_index);
  680. format.for_each_calendar_field_zipped_with(date_format, [](auto& field, auto const& date_field, auto) {
  681. if (date_field.has_value())
  682. field = date_field;
  683. });
  684. format.for_each_calendar_field_zipped_with(time_format, [](auto& field, auto const& time_field, auto) {
  685. if (time_field.has_value())
  686. field = time_field;
  687. });
  688. append_if_unique(move(format));
  689. }
  690. }
  691. }
  692. static void parse_calendar_symbols(Calendar& calendar, JsonObject const& calendar_object, UnicodeLocaleData& locale_data)
  693. {
  694. auto ensure_symbols = [&](auto name, size_t size) -> CalendarSymbols& {
  695. if (!locale_data.symbols.contains_slow(name))
  696. locale_data.symbols.append(name);
  697. return calendar.symbols.ensure(name, [&]() {
  698. CalendarSymbols symbols {};
  699. symbols.narrow_symbols.resize(size);
  700. symbols.short_symbols.resize(size);
  701. symbols.long_symbols.resize(size);
  702. return symbols;
  703. });
  704. };
  705. auto parse_era_symbols = [&](auto const& symbols_object) {
  706. auto const& narrow_symbols = symbols_object.get("eraNarrow"sv).as_object();
  707. auto const& short_symbols = symbols_object.get("eraAbbr"sv).as_object();
  708. auto const& long_symbols = symbols_object.get("eraNames"sv).as_object();
  709. auto& symbols = ensure_symbols("era"sv, 2);
  710. auto append_symbol = [&](auto& symbols, auto const& key, auto symbol) {
  711. if (auto key_index = key.to_uint(); key_index.has_value())
  712. symbols[*key_index] = locale_data.unique_strings.ensure(move(symbol));
  713. };
  714. narrow_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  715. append_symbol(symbols.narrow_symbols, key, value.as_string());
  716. });
  717. short_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  718. append_symbol(symbols.short_symbols, key, value.as_string());
  719. });
  720. long_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  721. append_symbol(symbols.long_symbols, key, value.as_string());
  722. });
  723. };
  724. auto parse_month_symbols = [&](auto const& symbols_object) {
  725. auto const& narrow_symbols = symbols_object.get("narrow"sv).as_object();
  726. auto const& short_symbols = symbols_object.get("abbreviated"sv).as_object();
  727. auto const& long_symbols = symbols_object.get("wide"sv).as_object();
  728. auto& month_symbols = ensure_symbols("month"sv, 12);
  729. auto append_symbol = [&](auto& symbols, auto const& key, auto symbol) {
  730. auto key_index = key.to_uint().value() - 1;
  731. symbols[key_index] = locale_data.unique_strings.ensure(move(symbol));
  732. };
  733. narrow_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  734. append_symbol(month_symbols.narrow_symbols, key, value.as_string());
  735. });
  736. short_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  737. append_symbol(month_symbols.short_symbols, key, value.as_string());
  738. });
  739. long_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  740. append_symbol(month_symbols.long_symbols, key, value.as_string());
  741. });
  742. };
  743. auto parse_weekday_symbols = [&](auto const& symbols_object) {
  744. auto const& narrow_symbols = symbols_object.get("narrow"sv).as_object();
  745. auto const& short_symbols = symbols_object.get("abbreviated"sv).as_object();
  746. auto const& long_symbols = symbols_object.get("wide"sv).as_object();
  747. auto& weekday_symbols = ensure_symbols("weekday"sv, 7);
  748. auto append_symbol = [&](auto& symbols, auto const& key, auto symbol) {
  749. if (key == "sun"sv)
  750. symbols[to_underlying(Unicode::Weekday::Sunday)] = locale_data.unique_strings.ensure(move(symbol));
  751. else if (key == "mon"sv)
  752. symbols[to_underlying(Unicode::Weekday::Monday)] = locale_data.unique_strings.ensure(move(symbol));
  753. else if (key == "tue"sv)
  754. symbols[to_underlying(Unicode::Weekday::Tuesday)] = locale_data.unique_strings.ensure(move(symbol));
  755. else if (key == "wed"sv)
  756. symbols[to_underlying(Unicode::Weekday::Wednesday)] = locale_data.unique_strings.ensure(move(symbol));
  757. else if (key == "thu"sv)
  758. symbols[to_underlying(Unicode::Weekday::Thursday)] = locale_data.unique_strings.ensure(move(symbol));
  759. else if (key == "fri"sv)
  760. symbols[to_underlying(Unicode::Weekday::Friday)] = locale_data.unique_strings.ensure(move(symbol));
  761. else if (key == "sat"sv)
  762. symbols[to_underlying(Unicode::Weekday::Saturday)] = locale_data.unique_strings.ensure(move(symbol));
  763. };
  764. narrow_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  765. append_symbol(weekday_symbols.narrow_symbols, key, value.as_string());
  766. });
  767. short_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  768. append_symbol(weekday_symbols.short_symbols, key, value.as_string());
  769. });
  770. long_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  771. append_symbol(weekday_symbols.long_symbols, key, value.as_string());
  772. });
  773. };
  774. auto parse_day_period_symbols = [&](auto const& symbols_object) {
  775. auto const& narrow_symbols = symbols_object.get("narrow"sv).as_object();
  776. auto const& short_symbols = symbols_object.get("abbreviated"sv).as_object();
  777. auto const& long_symbols = symbols_object.get("wide"sv).as_object();
  778. auto& day_period_symbols = ensure_symbols("dayPeriod"sv, 10);
  779. auto append_symbol = [&](auto& symbols, auto const& key, auto symbol) {
  780. if (auto day_period = day_period_from_string(key); day_period.has_value())
  781. symbols[to_underlying(*day_period)] = locale_data.unique_strings.ensure(move(symbol));
  782. };
  783. narrow_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  784. append_symbol(day_period_symbols.narrow_symbols, key, value.as_string());
  785. });
  786. short_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  787. append_symbol(day_period_symbols.short_symbols, key, value.as_string());
  788. });
  789. long_symbols.for_each_member([&](auto const& key, JsonValue const& value) {
  790. append_symbol(day_period_symbols.long_symbols, key, value.as_string());
  791. });
  792. };
  793. parse_era_symbols(calendar_object.get("eras"sv).as_object());
  794. parse_month_symbols(calendar_object.get("months"sv).as_object().get("format"sv).as_object());
  795. parse_weekday_symbols(calendar_object.get("days"sv).as_object().get("format"sv).as_object());
  796. parse_day_period_symbols(calendar_object.get("dayPeriods"sv).as_object().get("format"sv).as_object());
  797. }
  798. static ErrorOr<void> parse_calendars(String locale_calendars_path, UnicodeLocaleData& locale_data, Locale& locale)
  799. {
  800. LexicalPath calendars_path(move(locale_calendars_path));
  801. if (!calendars_path.basename().starts_with("ca-"sv))
  802. return {};
  803. auto calendars_file = TRY(Core::File::open(calendars_path.string(), Core::OpenMode::ReadOnly));
  804. auto calendars = TRY(JsonValue::from_string(calendars_file->read_all()));
  805. auto const& main_object = calendars.as_object().get("main"sv);
  806. auto const& locale_object = main_object.as_object().get(calendars_path.parent().basename());
  807. auto const& dates_object = locale_object.as_object().get("dates"sv);
  808. auto const& calendars_object = dates_object.as_object().get("calendars"sv);
  809. auto ensure_calendar = [&](auto const& calendar) -> Calendar& {
  810. return locale.calendars.ensure(calendar, [&]() {
  811. auto calendar_index = locale_data.unique_strings.ensure(calendar);
  812. return Calendar { .calendar = calendar_index };
  813. });
  814. };
  815. auto parse_patterns = [&](auto& formats, auto const& patterns_object, auto const& skeletons_object, Vector<CalendarPattern>* patterns) {
  816. auto parse_pattern = [&](auto name) {
  817. auto format = patterns_object.get(name);
  818. auto skeleton = skeletons_object.get(name);
  819. auto format_index = parse_date_time_pattern(format.as_string(), skeleton.as_string_or(String::empty()), locale_data).value();
  820. if (patterns)
  821. patterns->append(locale_data.unique_patterns.get(format_index));
  822. return format_index;
  823. };
  824. formats.full_format = parse_pattern("full"sv);
  825. formats.long_format = parse_pattern("long"sv);
  826. formats.medium_format = parse_pattern("medium"sv);
  827. formats.short_format = parse_pattern("short"sv);
  828. };
  829. calendars_object.as_object().for_each_member([&](auto const& calendar_name, JsonValue const& value) {
  830. // The generic calendar is not a supported Unicode calendar key, so skip it:
  831. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#unicode_calendar_keys
  832. if (calendar_name == "generic"sv)
  833. return;
  834. auto& calendar = ensure_calendar(calendar_name);
  835. if (!locale_data.calendars.contains_slow(calendar_name))
  836. locale_data.calendars.append(calendar_name);
  837. Vector<CalendarPattern> date_formats;
  838. Vector<CalendarPattern> time_formats;
  839. auto const& date_formats_object = value.as_object().get("dateFormats"sv);
  840. auto const& date_skeletons_object = value.as_object().get("dateSkeletons"sv);
  841. parse_patterns(calendar.date_formats, date_formats_object.as_object(), date_skeletons_object.as_object(), &date_formats);
  842. auto const& time_formats_object = value.as_object().get("timeFormats"sv);
  843. auto const& time_skeletons_object = value.as_object().get("timeSkeletons"sv);
  844. parse_patterns(calendar.time_formats, time_formats_object.as_object(), time_skeletons_object.as_object(), &time_formats);
  845. auto const& date_time_formats_object = value.as_object().get("dateTimeFormats"sv);
  846. parse_patterns(calendar.date_time_formats, date_time_formats_object.as_object(), JsonObject {}, nullptr);
  847. auto const& available_formats = date_time_formats_object.as_object().get("availableFormats"sv);
  848. available_formats.as_object().for_each_member([&](auto const& skeleton, JsonValue const& pattern) {
  849. auto pattern_index = parse_date_time_pattern(pattern.as_string(), skeleton, locale_data);
  850. if (!pattern_index.has_value())
  851. return;
  852. auto const& format = locale_data.unique_patterns.get(*pattern_index);
  853. if (format.contains_only_date_fields())
  854. date_formats.append(format);
  855. else if (format.contains_only_time_fields())
  856. time_formats.append(format);
  857. if (!calendar.available_formats.contains_slow(*pattern_index))
  858. calendar.available_formats.append(*pattern_index);
  859. });
  860. auto const& interval_formats_object = date_time_formats_object.as_object().get("intervalFormats"sv);
  861. parse_interval_patterns(calendar, interval_formats_object.as_object(), locale_data);
  862. generate_missing_patterns(calendar, move(date_formats), move(time_formats), locale_data);
  863. parse_calendar_symbols(calendar, value.as_object(), locale_data);
  864. });
  865. return {};
  866. }
  867. static ErrorOr<void> parse_time_zone_names(String locale_time_zone_names_path, UnicodeLocaleData& locale_data, Locale& locale)
  868. {
  869. LexicalPath time_zone_names_path(move(locale_time_zone_names_path));
  870. time_zone_names_path = time_zone_names_path.append("timeZoneNames.json"sv);
  871. auto time_zone_names_file = TRY(Core::File::open(time_zone_names_path.string(), Core::OpenMode::ReadOnly));
  872. auto time_zone_names = TRY(JsonValue::from_string(time_zone_names_file->read_all()));
  873. auto const& main_object = time_zone_names.as_object().get("main"sv);
  874. auto const& locale_object = main_object.as_object().get(time_zone_names_path.parent().basename());
  875. auto const& dates_object = locale_object.as_object().get("dates"sv);
  876. auto const& time_zone_names_object = dates_object.as_object().get("timeZoneNames"sv);
  877. auto const& meta_zone_object = time_zone_names_object.as_object().get("metazone"sv);
  878. if (meta_zone_object.is_null())
  879. return {};
  880. auto parse_name = [&](StringView type, JsonObject const& meta_zone_object) -> Optional<StringIndexType> {
  881. auto const& names = meta_zone_object.get(type);
  882. if (!names.is_object())
  883. return {};
  884. auto const& daylight = names.as_object().get("daylight"sv);
  885. if (daylight.is_string())
  886. return locale_data.unique_strings.ensure(daylight.as_string());
  887. auto const& standard = names.as_object().get("standard"sv);
  888. if (standard.is_string())
  889. return locale_data.unique_strings.ensure(standard.as_string());
  890. return {};
  891. };
  892. auto parse_time_zone = [&](StringView meta_zone, JsonObject const& meta_zone_object) {
  893. auto golden_zone = locale_data.meta_zones.get(meta_zone).value();
  894. TimeZone time_zone { .time_zone = golden_zone };
  895. if (auto long_name = parse_name("long"sv, meta_zone_object); long_name.has_value())
  896. time_zone.long_name = long_name.value();
  897. if (auto short_name = parse_name("short"sv, meta_zone_object); short_name.has_value())
  898. time_zone.short_name = short_name.value();
  899. auto const& time_zone_name = locale_data.unique_strings.get(golden_zone);
  900. if (!locale_data.time_zones.contains_slow(time_zone_name))
  901. locale_data.time_zones.append(time_zone_name);
  902. locale.time_zones.set(time_zone_name, move(time_zone));
  903. };
  904. meta_zone_object.as_object().for_each_member([&](auto const& meta_zone, JsonValue const& value) {
  905. parse_time_zone(meta_zone, value.as_object());
  906. });
  907. // The long and short names for UTC are not under the "timeZoneNames/metazone" object, but are under "timeZoneNames/zone/Etc".
  908. auto const& zone_object = time_zone_names_object.as_object().get("zone"sv);
  909. auto const& etc_object = zone_object.as_object().get("Etc"sv);
  910. auto const& utc_object = etc_object.as_object().get("UTC"sv);
  911. parse_time_zone("UTC"sv, utc_object.as_object());
  912. return {};
  913. }
  914. static ErrorOr<void> parse_day_periods(String core_path, UnicodeLocaleData& locale_data)
  915. {
  916. // https://unicode.org/reports/tr35/tr35-dates.html#Day_Period_Rule_Sets
  917. LexicalPath day_periods_path(move(core_path));
  918. day_periods_path = day_periods_path.append("supplemental"sv);
  919. day_periods_path = day_periods_path.append("dayPeriods.json"sv);
  920. auto day_periods_file = TRY(Core::File::open(day_periods_path.string(), Core::OpenMode::ReadOnly));
  921. auto day_periods = TRY(JsonValue::from_string(day_periods_file->read_all()));
  922. auto const& supplemental_object = day_periods.as_object().get("supplemental"sv);
  923. auto const& day_periods_object = supplemental_object.as_object().get("dayPeriodRuleSet"sv);
  924. auto parse_hour = [](auto const& time) {
  925. auto hour_end_index = time.find(':').value();
  926. // The times are in the form "hours:minutes", but we only need the hour segment.
  927. // TR-35 explicitly states that minutes other than :00 must not be used.
  928. VERIFY(time.substring_view(hour_end_index) == ":00"sv);
  929. auto hour = time.substring_view(0, hour_end_index);
  930. return hour.template to_uint<u8>().value();
  931. };
  932. auto parse_day_period = [&](auto const& symbol, auto const& ranges) -> Optional<DayPeriod> {
  933. auto day_period = day_period_from_string(symbol);
  934. if (!day_period.has_value())
  935. return {};
  936. auto begin = parse_hour(ranges.get("_from"sv).as_string());
  937. auto end = parse_hour(ranges.get("_before"sv).as_string());
  938. return DayPeriod { *day_period, begin, end };
  939. };
  940. day_periods_object.as_object().for_each_member([&](auto const& language, JsonValue const& value) {
  941. auto locale = locale_data.locales.find(language);
  942. if (locale == locale_data.locales.end())
  943. return;
  944. value.as_object().for_each_member([&](auto const& symbol, JsonValue const& ranges) {
  945. if (auto day_period = parse_day_period(symbol, ranges.as_object()); day_period.has_value())
  946. locale->value.day_periods.append(day_period.release_value());
  947. });
  948. });
  949. return {};
  950. };
  951. static ErrorOr<void> parse_all_locales(String core_path, String dates_path, UnicodeLocaleData& locale_data)
  952. {
  953. TRY(parse_hour_cycles(core_path, locale_data));
  954. TRY(parse_meta_zones(core_path, locale_data));
  955. auto dates_iterator = TRY(path_to_dir_iterator(move(dates_path)));
  956. auto remove_variants_from_path = [&](String path) -> ErrorOr<String> {
  957. auto parsed_locale = TRY(CanonicalLanguageID<StringIndexType>::parse(locale_data.unique_strings, LexicalPath::basename(path)));
  958. StringBuilder builder;
  959. builder.append(locale_data.unique_strings.get(parsed_locale.language));
  960. if (auto script = locale_data.unique_strings.get(parsed_locale.script); !script.is_empty())
  961. builder.appendff("-{}", script);
  962. if (auto region = locale_data.unique_strings.get(parsed_locale.region); !region.is_empty())
  963. builder.appendff("-{}", region);
  964. return builder.build();
  965. };
  966. while (dates_iterator.has_next()) {
  967. auto dates_path = TRY(next_path_from_dir_iterator(dates_iterator));
  968. auto calendars_iterator = TRY(path_to_dir_iterator(dates_path, {}));
  969. auto language = TRY(remove_variants_from_path(dates_path));
  970. auto& locale = locale_data.locales.ensure(language);
  971. while (calendars_iterator.has_next()) {
  972. auto calendars_path = TRY(next_path_from_dir_iterator(calendars_iterator));
  973. TRY(parse_calendars(move(calendars_path), locale_data, locale));
  974. }
  975. TRY(parse_time_zone_names(move(dates_path), locale_data, locale));
  976. }
  977. TRY(parse_day_periods(move(core_path), locale_data));
  978. return {};
  979. }
  980. static String format_identifier(StringView owner, String identifier)
  981. {
  982. identifier = identifier.replace("-"sv, "_"sv, true);
  983. identifier = identifier.replace("/"sv, "_"sv, true);
  984. if (all_of(identifier, is_ascii_digit))
  985. return String::formatted("{}_{}", owner[0], identifier);
  986. if (is_ascii_lower_alpha(identifier[0]))
  987. return String::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  988. return identifier;
  989. }
  990. static void generate_unicode_locale_header(Core::File& file, UnicodeLocaleData& locale_data)
  991. {
  992. StringBuilder builder;
  993. SourceGenerator generator { builder };
  994. generator.append(R"~~~(
  995. #pragma once
  996. #include <AK/Optional.h>
  997. #include <AK/StringView.h>
  998. #include <LibUnicode/Forward.h>
  999. namespace Unicode {
  1000. )~~~");
  1001. generate_enum(generator, format_identifier, "Calendar"sv, {}, locale_data.calendars, locale_data.calendar_aliases);
  1002. generate_enum(generator, format_identifier, "HourCycleRegion"sv, {}, locale_data.hour_cycle_regions);
  1003. generate_enum(generator, format_identifier, "CalendarSymbol"sv, {}, locale_data.symbols);
  1004. generate_enum(generator, format_identifier, "TimeZone"sv, {}, locale_data.time_zones);
  1005. generator.append(R"~~~(
  1006. namespace Detail {
  1007. Optional<Calendar> calendar_from_string(StringView calendar);
  1008. Optional<HourCycleRegion> hour_cycle_region_from_string(StringView hour_cycle_region);
  1009. Vector<Unicode::HourCycle> get_regional_hour_cycles(StringView region);
  1010. Optional<Unicode::CalendarFormat> get_calendar_date_format(StringView locale, StringView calendar);
  1011. Optional<Unicode::CalendarFormat> get_calendar_time_format(StringView locale, StringView calendar);
  1012. Optional<Unicode::CalendarFormat> get_calendar_date_time_format(StringView locale, StringView calendar);
  1013. Vector<Unicode::CalendarPattern> get_calendar_available_formats(StringView locale, StringView calendar);
  1014. Optional<Unicode::CalendarRangePattern> get_calendar_default_range_format(StringView locale, StringView calendar);
  1015. Vector<Unicode::CalendarRangePattern> get_calendar_range_formats(StringView locale, StringView calendar, StringView skeleton);
  1016. Vector<Unicode::CalendarRangePattern> get_calendar_range12_formats(StringView locale, StringView calendar, StringView skeleton);
  1017. Optional<StringView> get_calendar_era_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::Era value);
  1018. Optional<StringView> get_calendar_month_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::Month value);
  1019. Optional<StringView> get_calendar_weekday_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::Weekday value);
  1020. Optional<StringView> get_calendar_day_period_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::DayPeriod value);
  1021. Optional<StringView> get_calendar_day_period_symbol_for_hour(StringView locale, StringView calendar, CalendarPatternStyle style, u8 hour);
  1022. Optional<TimeZone> time_zone_from_string(StringView time_zone);
  1023. Optional<StringView> get_time_zone_name(StringView locale, StringView time_zone, CalendarPatternStyle style);
  1024. }
  1025. }
  1026. )~~~");
  1027. VERIFY(file.write(generator.as_string_view()));
  1028. }
  1029. static void generate_unicode_locale_implementation(Core::File& file, UnicodeLocaleData& locale_data)
  1030. {
  1031. StringBuilder builder;
  1032. SourceGenerator generator { builder };
  1033. generator.set("string_index_type"sv, s_string_index_type);
  1034. generator.set("calendar_pattern_index_type"sv, s_calendar_pattern_index_type);
  1035. generator.set("calendar_range_pattern_index_type"sv, s_calendar_range_pattern_index_type);
  1036. generator.set("calendar_symbols_size"sv, String::number(locale_data.symbols.size()));
  1037. generator.append(R"~~~(
  1038. #include <AK/Array.h>
  1039. #include <AK/BinarySearch.h>
  1040. #include <LibUnicode/DateTimeFormat.h>
  1041. #include <LibUnicode/Locale.h>
  1042. #include <LibUnicode/UnicodeDateTimeFormat.h>
  1043. namespace Unicode::Detail {
  1044. )~~~");
  1045. locale_data.unique_strings.generate(generator);
  1046. generator.append(R"~~~(
  1047. template <typename SourceType, typename TargetType>
  1048. void convert_calendar_fields(SourceType const& source, TargetType& target)
  1049. {
  1050. if (source.era != -1)
  1051. target.era = static_cast<Unicode::CalendarPatternStyle>(source.era);
  1052. if (source.year != -1)
  1053. target.year = static_cast<Unicode::CalendarPatternStyle>(source.year);
  1054. if (source.month != -1)
  1055. target.month = static_cast<Unicode::CalendarPatternStyle>(source.month);
  1056. if (source.weekday != -1)
  1057. target.weekday = static_cast<Unicode::CalendarPatternStyle>(source.weekday);
  1058. if (source.day != -1)
  1059. target.day = static_cast<Unicode::CalendarPatternStyle>(source.day);
  1060. if (source.day_period != -1)
  1061. target.day_period = static_cast<Unicode::CalendarPatternStyle>(source.day_period);
  1062. if (source.hour != -1)
  1063. target.hour = static_cast<Unicode::CalendarPatternStyle>(source.hour);
  1064. if (source.minute != -1)
  1065. target.minute = static_cast<Unicode::CalendarPatternStyle>(source.minute);
  1066. if (source.second != -1)
  1067. target.second = static_cast<Unicode::CalendarPatternStyle>(source.second);
  1068. if (source.fractional_second_digits != -1)
  1069. target.fractional_second_digits = static_cast<u8>(source.fractional_second_digits);
  1070. if (source.time_zone_name != -1)
  1071. target.time_zone_name = static_cast<Unicode::CalendarPatternStyle>(source.time_zone_name);
  1072. }
  1073. struct CalendarPattern {
  1074. Unicode::CalendarPattern to_unicode_calendar_pattern() const {
  1075. Unicode::CalendarPattern calendar_pattern {};
  1076. calendar_pattern.skeleton = s_string_list[skeleton];
  1077. calendar_pattern.pattern = s_string_list[pattern];
  1078. if (pattern12 != 0)
  1079. calendar_pattern.pattern12 = s_string_list[pattern12];
  1080. convert_calendar_fields(*this, calendar_pattern);
  1081. return calendar_pattern;
  1082. }
  1083. @string_index_type@ skeleton { 0 };
  1084. @string_index_type@ pattern { 0 };
  1085. @string_index_type@ pattern12 { 0 };
  1086. i8 era { -1 };
  1087. i8 year { -1 };
  1088. i8 month { -1 };
  1089. i8 weekday { -1 };
  1090. i8 day { -1 };
  1091. i8 day_period { -1 };
  1092. i8 hour { -1 };
  1093. i8 minute { -1 };
  1094. i8 second { -1 };
  1095. i8 fractional_second_digits { -1 };
  1096. i8 time_zone_name { -1 };
  1097. };
  1098. struct CalendarRangePattern {
  1099. Unicode::CalendarRangePattern to_unicode_calendar_range_pattern() const {
  1100. Unicode::CalendarRangePattern calendar_range_pattern {};
  1101. if (field != -1)
  1102. calendar_range_pattern.field = static_cast<Unicode::CalendarRangePattern::Field>(field);
  1103. calendar_range_pattern.start_range = s_string_list[start_range];
  1104. calendar_range_pattern.separator = s_string_list[separator];
  1105. calendar_range_pattern.end_range = s_string_list[end_range];
  1106. convert_calendar_fields(*this, calendar_range_pattern);
  1107. return calendar_range_pattern;
  1108. }
  1109. @string_index_type@ skeleton { 0 };
  1110. i8 field { -1 };
  1111. @string_index_type@ start_range { 0 };
  1112. @string_index_type@ separator { 0 };
  1113. @string_index_type@ end_range { 0 };
  1114. i8 era { -1 };
  1115. i8 year { -1 };
  1116. i8 month { -1 };
  1117. i8 weekday { -1 };
  1118. i8 day { -1 };
  1119. i8 day_period { -1 };
  1120. i8 hour { -1 };
  1121. i8 minute { -1 };
  1122. i8 second { -1 };
  1123. i8 fractional_second_digits { -1 };
  1124. i8 time_zone_name { -1 };
  1125. };
  1126. )~~~");
  1127. locale_data.unique_patterns.generate(generator, "CalendarPattern"sv, "s_calendar_patterns"sv, 10);
  1128. locale_data.unique_range_patterns.generate(generator, "CalendarRangePattern"sv, "s_calendar_range_patterns"sv, 10);
  1129. generator.append(R"~~~(
  1130. struct CalendarFormat {
  1131. Unicode::CalendarFormat to_unicode_calendar_format() const {
  1132. Unicode::CalendarFormat calendar_format {};
  1133. calendar_format.full_format = s_calendar_patterns[full_format].to_unicode_calendar_pattern();
  1134. calendar_format.long_format = s_calendar_patterns[long_format].to_unicode_calendar_pattern();
  1135. calendar_format.medium_format = s_calendar_patterns[medium_format].to_unicode_calendar_pattern();
  1136. calendar_format.short_format = s_calendar_patterns[short_format].to_unicode_calendar_pattern();
  1137. return calendar_format;
  1138. }
  1139. @calendar_pattern_index_type@ full_format { 0 };
  1140. @calendar_pattern_index_type@ long_format { 0 };
  1141. @calendar_pattern_index_type@ medium_format { 0 };
  1142. @calendar_pattern_index_type@ short_format { 0 };
  1143. };
  1144. using CalendarSymbols = Span<@string_index_type@ const>;
  1145. struct CalendarData {
  1146. @string_index_type@ calendar { 0 };
  1147. CalendarFormat date_formats {};
  1148. CalendarFormat time_formats {};
  1149. CalendarFormat date_time_formats {};
  1150. Span<@calendar_pattern_index_type@ const> available_formats {};
  1151. @calendar_range_pattern_index_type@ default_range_format { 0 };
  1152. Span<@calendar_range_pattern_index_type@ const> range_formats {};
  1153. Span<@calendar_range_pattern_index_type@ const> range12_formats {};
  1154. Array<Span<CalendarSymbols const>, @calendar_symbols_size@> symbols {};
  1155. };
  1156. struct TimeZoneData {
  1157. @string_index_type@ time_zone { 0 };
  1158. @string_index_type@ long_name { 0 };
  1159. @string_index_type@ short_name { 0 };
  1160. };
  1161. struct DayPeriodData {
  1162. u8 day_period { 0 };
  1163. u8 begin { 0 };
  1164. u8 end { 0 };
  1165. };
  1166. )~~~");
  1167. auto append_pattern_list = [&](auto name, auto type, auto const& formats) {
  1168. generator.set("name", move(name));
  1169. generator.set("type", move(type));
  1170. generator.set("size", String::number(formats.size()));
  1171. generator.append(R"~~~(
  1172. static constexpr Array<@type@, @size@> @name@ { {)~~~");
  1173. bool first = true;
  1174. for (auto format : formats) {
  1175. generator.append(first ? " " : ", ");
  1176. generator.append(String::number(format));
  1177. first = false;
  1178. }
  1179. generator.append(" } };");
  1180. };
  1181. auto append_calendar_format = [&](auto const& calendar_format) {
  1182. generator.set("full_format", String::number(calendar_format.full_format));
  1183. generator.set("long_format", String::number(calendar_format.long_format));
  1184. generator.set("medium_format", String::number(calendar_format.medium_format));
  1185. generator.set("short_format", String::number(calendar_format.short_format));
  1186. generator.append("{ @full_format@, @long_format@, @medium_format@, @short_format@ },");
  1187. };
  1188. auto append_calendar_symbols_for_style = [&](auto name, auto style, auto const& symbols) {
  1189. name = String::formatted("{}_{}", name, style);
  1190. generator.set("name", name);
  1191. generator.set("size", String::number(symbols.size()));
  1192. generator.append(R"~~~(
  1193. static constexpr Array<@string_index_type@, @size@> @name@ { {)~~~");
  1194. bool first = true;
  1195. for (auto symbol : symbols) {
  1196. generator.append(first ? " " : ", ");
  1197. generator.append(String::number(symbol));
  1198. first = false;
  1199. }
  1200. generator.append(" } };");
  1201. return name;
  1202. };
  1203. auto append_calendar_symbols = [&](auto name, auto symbol, auto const& symbols) {
  1204. name = String::formatted("{}_{}", name, symbol.to_lowercase());
  1205. auto narrow_symbols = append_calendar_symbols_for_style(name, "narrow"sv, symbols.narrow_symbols);
  1206. auto short_symbols = append_calendar_symbols_for_style(name, "short"sv, symbols.short_symbols);
  1207. auto long_symbols = append_calendar_symbols_for_style(name, "long"sv, symbols.long_symbols);
  1208. generator.set("narrow_symbols", move(narrow_symbols));
  1209. generator.set("short_symbols", move(short_symbols));
  1210. generator.set("long_symbols", move(long_symbols));
  1211. generator.set("name", name);
  1212. generator.append(R"~~~(
  1213. static constexpr Array<CalendarSymbols, 3> @name@ { @narrow_symbols@.span(), @short_symbols@.span(), @long_symbols@.span() };
  1214. )~~~");
  1215. return name;
  1216. };
  1217. auto append_calendars = [&](String name, auto const& calendars) {
  1218. auto format_name = [&](StringView calendar_key, StringView type) {
  1219. return String::formatted("{}_{}_{}", name, calendar_key, type);
  1220. };
  1221. Vector<String> symbols_names;
  1222. for (auto const& calendar_key : locale_data.calendars) {
  1223. auto const& calendar = calendars.find(calendar_key)->value;
  1224. append_pattern_list(format_name(calendar_key, "formats"sv), s_calendar_pattern_index_type, calendar.available_formats);
  1225. append_pattern_list(format_name(calendar_key, "range_formats"sv), s_calendar_range_pattern_index_type, calendar.range_formats);
  1226. append_pattern_list(format_name(calendar_key, "range12_formats"sv), s_calendar_range_pattern_index_type, calendar.range12_formats);
  1227. generator.append("\n");
  1228. auto symbols_name = format_name(calendar_key, "symbols"sv);
  1229. for (auto const& symbol_key : locale_data.symbols) {
  1230. auto const& symbols = calendar.symbols.find(symbol_key)->value;
  1231. auto name = append_calendar_symbols(symbols_name, symbol_key, symbols);
  1232. symbols_names.append(name);
  1233. }
  1234. }
  1235. generator.set("name", name);
  1236. generator.set("size", String::number(calendars.size()));
  1237. generator.append(R"~~~(
  1238. static constexpr Array<CalendarData, @size@> @name@ { {)~~~");
  1239. for (auto const& calendar_key : locale_data.calendars) {
  1240. auto const& calendar = calendars.find(calendar_key)->value;
  1241. generator.set("formats", format_name(calendar_key, "formats"sv));
  1242. generator.set("default_range_format", String::number(calendar.default_range_format));
  1243. generator.set("range_formats", format_name(calendar_key, "range_formats"sv));
  1244. generator.set("range12_formats", format_name(calendar_key, "range12_formats"sv));
  1245. generator.set("calendar"sv, String::number(calendar.calendar));
  1246. generator.append(R"~~~(
  1247. { @calendar@, )~~~");
  1248. append_calendar_format(calendar.date_formats);
  1249. generator.append(" ");
  1250. append_calendar_format(calendar.time_formats);
  1251. generator.append(" ");
  1252. append_calendar_format(calendar.date_time_formats);
  1253. generator.append(" @formats@.span(), @default_range_format@, @range_formats@.span(), @range12_formats@.span(), {");
  1254. bool first = true;
  1255. for (auto const& symbols_name : symbols_names) {
  1256. generator.append(first ? " " : ", ");
  1257. generator.append(String::formatted("{}.span()", symbols_name));
  1258. first = false;
  1259. }
  1260. generator.append(" } },");
  1261. }
  1262. generator.append(R"~~~(
  1263. } };
  1264. )~~~");
  1265. };
  1266. auto append_time_zones = [&](String name, auto const& time_zones) {
  1267. generator.set("name", name);
  1268. generator.set("size", String::number(locale_data.time_zones.size()));
  1269. generator.append(R"~~~(
  1270. static constexpr Array<TimeZoneData, @size@> @name@ { {)~~~");
  1271. constexpr size_t max_values_per_row = 20;
  1272. size_t values_in_current_row = 0;
  1273. for (auto const& time_zone_key : locale_data.time_zones) {
  1274. auto time_zone = time_zones.find(time_zone_key);
  1275. if (values_in_current_row++ > 0)
  1276. generator.append(" ");
  1277. if (time_zone == time_zones.end()) {
  1278. generator.append("{},");
  1279. } else {
  1280. generator.set("time_zone", String::number(time_zone->value.time_zone));
  1281. generator.set("long_name", String::number(time_zone->value.long_name));
  1282. generator.set("short_name", String::number(time_zone->value.short_name));
  1283. generator.append("{ @time_zone@, @long_name@, @short_name@ },");
  1284. }
  1285. if (values_in_current_row == max_values_per_row) {
  1286. values_in_current_row = 0;
  1287. generator.append("\n ");
  1288. }
  1289. }
  1290. generator.append(R"~~~(
  1291. } };
  1292. )~~~");
  1293. };
  1294. auto append_day_periods = [&](String name, auto const& day_periods) {
  1295. generator.set("name", move(name));
  1296. generator.set("size", String::number(day_periods.size()));
  1297. generator.append(R"~~~(
  1298. static constexpr Array<DayPeriodData, @size@> @name@ { {)~~~");
  1299. for (auto const& day_period : day_periods) {
  1300. generator.set("day_period", String::number(static_cast<u8>(day_period.day_period)));
  1301. generator.set("begin", String::number(day_period.begin));
  1302. generator.set("end", String::number(day_period.end));
  1303. generator.append(" { @day_period@, @begin@, @end@ },");
  1304. }
  1305. generator.append(" } };");
  1306. };
  1307. auto append_hour_cycles = [&](String name, auto const& hour_cycle_region) {
  1308. auto const& hour_cycles = locale_data.hour_cycles.find(hour_cycle_region)->value;
  1309. generator.set("name", name);
  1310. generator.set("size", String::number(hour_cycles.size()));
  1311. generator.append(R"~~~(
  1312. static constexpr Array<u8, @size@> @name@ { { )~~~");
  1313. for (auto hour_cycle : hour_cycles) {
  1314. generator.set("hour_cycle", String::number(static_cast<u8>(hour_cycle)));
  1315. generator.append("@hour_cycle@, ");
  1316. }
  1317. generator.append(" } };");
  1318. };
  1319. generate_mapping(generator, locale_data.locales, "CalendarData"sv, "s_calendars"sv, "s_calendars_{}", [&](auto const& name, auto const& value) { append_calendars(name, value.calendars); });
  1320. generate_mapping(generator, locale_data.locales, "TimeZoneData"sv, "s_time_zones"sv, "s_time_zones_{}", [&](auto const& name, auto const& value) { append_time_zones(name, value.time_zones); });
  1321. generate_mapping(generator, locale_data.locales, "DayPeriodData"sv, "s_day_periods"sv, "s_day_periods_{}", [&](auto const& name, auto const& value) { append_day_periods(name, value.day_periods); });
  1322. 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); });
  1323. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) {
  1324. HashValueMap<String> hashes;
  1325. hashes.ensure_capacity(values.size());
  1326. for (auto const& value : values)
  1327. hashes.set(value.hash(), format_identifier(enum_title, value));
  1328. for (auto const& alias : aliases)
  1329. hashes.set(alias.alias.hash(), format_identifier(enum_title, alias.alias));
  1330. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  1331. };
  1332. append_from_string("Calendar"sv, "calendar"sv, locale_data.calendars, locale_data.calendar_aliases);
  1333. append_from_string("HourCycleRegion"sv, "hour_cycle_region"sv, locale_data.hour_cycle_regions);
  1334. append_from_string("TimeZone"sv, "time_zone"sv, locale_data.time_zones);
  1335. generator.append(R"~~~(
  1336. Vector<Unicode::HourCycle> get_regional_hour_cycles(StringView region)
  1337. {
  1338. auto region_value = hour_cycle_region_from_string(region);
  1339. if (!region_value.has_value())
  1340. return {};
  1341. auto region_index = to_underlying(*region_value);
  1342. auto const& regional_hour_cycles = s_hour_cycles.at(region_index);
  1343. Vector<Unicode::HourCycle> hour_cycles;
  1344. hour_cycles.ensure_capacity(regional_hour_cycles.size());
  1345. for (auto hour_cycle : regional_hour_cycles)
  1346. hour_cycles.unchecked_append(static_cast<Unicode::HourCycle>(hour_cycle));
  1347. return hour_cycles;
  1348. }
  1349. static CalendarData const* find_calendar_data(StringView locale, StringView calendar)
  1350. {
  1351. auto locale_value = locale_from_string(locale);
  1352. if (!locale_value.has_value())
  1353. return nullptr;
  1354. auto calendar_value = calendar_from_string(calendar);
  1355. if (!calendar_value.has_value())
  1356. return nullptr;
  1357. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  1358. auto calendar_index = to_underlying(*calendar_value);
  1359. auto const& calendars = s_calendars.at(locale_index);
  1360. return &calendars[calendar_index];
  1361. }
  1362. Optional<Unicode::CalendarFormat> get_calendar_date_format(StringView locale, StringView calendar)
  1363. {
  1364. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  1365. return data->date_formats.to_unicode_calendar_format();
  1366. return {};
  1367. }
  1368. Optional<Unicode::CalendarFormat> get_calendar_time_format(StringView locale, StringView calendar)
  1369. {
  1370. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  1371. return data->time_formats.to_unicode_calendar_format();
  1372. return {};
  1373. }
  1374. Optional<Unicode::CalendarFormat> get_calendar_date_time_format(StringView locale, StringView calendar)
  1375. {
  1376. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  1377. return data->date_time_formats.to_unicode_calendar_format();
  1378. return {};
  1379. }
  1380. Vector<Unicode::CalendarPattern> get_calendar_available_formats(StringView locale, StringView calendar)
  1381. {
  1382. Vector<Unicode::CalendarPattern> result {};
  1383. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  1384. result.ensure_capacity(data->available_formats.size());
  1385. for (auto const& format : data->available_formats)
  1386. result.unchecked_append(s_calendar_patterns[format].to_unicode_calendar_pattern());
  1387. }
  1388. return result;
  1389. }
  1390. Optional<Unicode::CalendarRangePattern> get_calendar_default_range_format(StringView locale, StringView calendar)
  1391. {
  1392. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  1393. auto const& pattern = s_calendar_range_patterns[data->default_range_format];
  1394. return pattern.to_unicode_calendar_range_pattern();
  1395. }
  1396. return {};
  1397. }
  1398. Vector<Unicode::CalendarRangePattern> get_calendar_range_formats(StringView locale, StringView calendar, StringView skeleton) {
  1399. Vector<Unicode::CalendarRangePattern> result {};
  1400. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  1401. for (auto format : data->range_formats) {
  1402. auto const& pattern = s_calendar_range_patterns[format];
  1403. if (skeleton == s_string_list[pattern.skeleton])
  1404. result.append(pattern.to_unicode_calendar_range_pattern());
  1405. }
  1406. }
  1407. return result;
  1408. }
  1409. Vector<Unicode::CalendarRangePattern> get_calendar_range12_formats(StringView locale, StringView calendar, StringView skeleton) {
  1410. Vector<Unicode::CalendarRangePattern> result {};
  1411. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  1412. for (auto format : data->range12_formats) {
  1413. auto const& pattern = s_calendar_range_patterns[format];
  1414. if (skeleton == s_string_list[pattern.skeleton])
  1415. result.append(pattern.to_unicode_calendar_range_pattern());
  1416. }
  1417. }
  1418. return result;
  1419. }
  1420. static CalendarSymbols find_calendar_symbols(StringView locale, StringView calendar, CalendarSymbol symbol, CalendarPatternStyle style)
  1421. {
  1422. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  1423. auto symbol_index = to_underlying(symbol);
  1424. auto style_index = to_underlying(style);
  1425. auto symbols = data->symbols.at(symbol_index);
  1426. VERIFY(style_index < symbols.size());
  1427. return symbols.at(style_index);
  1428. }
  1429. return {};
  1430. }
  1431. Optional<StringView> get_calendar_era_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::Era value)
  1432. {
  1433. auto symbols = find_calendar_symbols(locale, calendar, CalendarSymbol::Era, style);
  1434. if (auto value_index = to_underlying(value); value_index < symbols.size())
  1435. return s_string_list[symbols.at(value_index)];
  1436. return {};
  1437. }
  1438. Optional<StringView> get_calendar_month_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::Month value)
  1439. {
  1440. auto symbols = find_calendar_symbols(locale, calendar, CalendarSymbol::Month, style);
  1441. if (auto value_index = to_underlying(value); value_index < symbols.size())
  1442. return s_string_list[symbols.at(value_index)];
  1443. return {};
  1444. }
  1445. Optional<StringView> get_calendar_weekday_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::Weekday value)
  1446. {
  1447. auto symbols = find_calendar_symbols(locale, calendar, CalendarSymbol::Weekday, style);
  1448. if (auto value_index = to_underlying(value); value_index < symbols.size())
  1449. return s_string_list[symbols.at(value_index)];
  1450. return {};
  1451. }
  1452. Optional<StringView> get_calendar_day_period_symbol(StringView locale, StringView calendar, CalendarPatternStyle style, Unicode::DayPeriod value)
  1453. {
  1454. auto symbols = find_calendar_symbols(locale, calendar, CalendarSymbol::DayPeriod, style);
  1455. if (auto value_index = to_underlying(value); value_index < symbols.size())
  1456. return s_string_list[symbols.at(value_index)];
  1457. return {};
  1458. }
  1459. Optional<StringView> get_calendar_day_period_symbol_for_hour(StringView locale, StringView calendar, CalendarPatternStyle style, u8 hour)
  1460. {
  1461. auto locale_value = locale_from_string(locale);
  1462. if (!locale_value.has_value())
  1463. return {};
  1464. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  1465. auto day_periods = s_day_periods[locale_index];
  1466. for (auto const& day_period : day_periods) {
  1467. if ((day_period.begin <= hour) && (hour < day_period.end)) {
  1468. auto period = static_cast<Unicode::DayPeriod>(day_period.day_period);
  1469. return Detail::get_calendar_day_period_symbol(locale, calendar, style, period);
  1470. }
  1471. }
  1472. // Fallback to fixed periods if the locale does not have flexible day periods.
  1473. // TR-35 states that the meaning of AM and PM does not change with locale.
  1474. if (hour < 12)
  1475. return Detail::get_calendar_day_period_symbol(locale, calendar, style, Unicode::DayPeriod::AM);
  1476. return Detail::get_calendar_day_period_symbol(locale, calendar, style, Unicode::DayPeriod::PM);
  1477. }
  1478. static TimeZoneData const* find_time_zone_data(StringView locale, StringView time_zone)
  1479. {
  1480. auto locale_value = locale_from_string(locale);
  1481. if (!locale_value.has_value())
  1482. return nullptr;
  1483. auto time_zone_value = time_zone_from_string(time_zone);
  1484. if (!time_zone_value.has_value())
  1485. return nullptr;
  1486. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  1487. auto time_zone_index = to_underlying(*time_zone_value);
  1488. auto const& time_zones = s_time_zones.at(locale_index);
  1489. return &time_zones[time_zone_index];
  1490. }
  1491. Optional<StringView> get_time_zone_name(StringView locale, StringView time_zone, CalendarPatternStyle style)
  1492. {
  1493. if (auto const* data = find_time_zone_data(locale, time_zone); data != nullptr) {
  1494. @string_index_type@ time_zone_index = 0;
  1495. switch (style) {
  1496. case CalendarPatternStyle::Long:
  1497. time_zone_index = data->long_name;
  1498. break;
  1499. case CalendarPatternStyle::Short:
  1500. time_zone_index = data->short_name;
  1501. break;
  1502. default:
  1503. VERIFY_NOT_REACHED();
  1504. }
  1505. if (time_zone_index != 0)
  1506. return s_string_list[time_zone_index];
  1507. }
  1508. return {};
  1509. }
  1510. }
  1511. )~~~");
  1512. VERIFY(file.write(generator.as_string_view()));
  1513. }
  1514. ErrorOr<int> serenity_main(Main::Arguments arguments)
  1515. {
  1516. StringView generated_header_path;
  1517. StringView generated_implementation_path;
  1518. StringView core_path;
  1519. StringView dates_path;
  1520. Core::ArgsParser args_parser;
  1521. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  1522. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  1523. args_parser.add_option(core_path, "Path to cldr-core directory", "core-path", 'r', "core-path");
  1524. args_parser.add_option(dates_path, "Path to cldr-dates directory", "dates-path", 'd', "dates-path");
  1525. args_parser.parse(arguments);
  1526. auto open_file = [&](StringView path) -> ErrorOr<NonnullRefPtr<Core::File>> {
  1527. if (path.is_empty()) {
  1528. args_parser.print_usage(stderr, arguments.argv[0]);
  1529. return Error::from_string_literal("Must provide all command line options"sv);
  1530. }
  1531. return Core::File::open(path, Core::OpenMode::ReadWrite);
  1532. };
  1533. auto generated_header_file = TRY(open_file(generated_header_path));
  1534. auto generated_implementation_file = TRY(open_file(generated_implementation_path));
  1535. UnicodeLocaleData locale_data;
  1536. TRY(parse_all_locales(core_path, dates_path, locale_data));
  1537. generate_unicode_locale_header(generated_header_file, locale_data);
  1538. generate_unicode_locale_implementation(generated_implementation_file, locale_data);
  1539. return 0;
  1540. }