GenerateUnicodeDateTimeFormat.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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/Format.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/JsonParser.h>
  11. #include <AK/JsonValue.h>
  12. #include <AK/LexicalPath.h>
  13. #include <AK/SourceGenerator.h>
  14. #include <AK/String.h>
  15. #include <AK/StringBuilder.h>
  16. #include <LibCore/ArgsParser.h>
  17. #include <LibCore/DirIterator.h>
  18. #include <LibCore/File.h>
  19. #include <LibUnicode/DateTimeFormat.h>
  20. using StringIndexType = u16;
  21. constexpr auto s_string_index_type = "u16"sv;
  22. struct CalendarPattern : public Unicode::CalendarPattern {
  23. StringIndexType pattern_index { 0 };
  24. };
  25. struct CalendarFormat {
  26. CalendarPattern full_format {};
  27. CalendarPattern long_format {};
  28. CalendarPattern medium_format {};
  29. CalendarPattern short_format {};
  30. };
  31. struct Calendar {
  32. StringIndexType calendar { 0 };
  33. CalendarFormat date_formats {};
  34. CalendarFormat time_formats {};
  35. CalendarFormat date_time_formats {};
  36. Vector<CalendarPattern> available_formats {};
  37. };
  38. struct Locale {
  39. HashMap<String, Calendar> calendars;
  40. };
  41. struct UnicodeLocaleData {
  42. UniqueStringStorage<StringIndexType> unique_strings;
  43. HashMap<String, Locale> locales;
  44. HashMap<String, Vector<Unicode::HourCycle>> hour_cycles;
  45. Vector<String> hour_cycle_regions;
  46. Vector<String> calendars;
  47. Vector<Alias> calendar_aliases {
  48. // FIXME: Aliases should come from BCP47. See: https://unicode-org.atlassian.net/browse/CLDR-15158
  49. { "gregorian"sv, "gregory"sv },
  50. };
  51. };
  52. static ErrorOr<void> parse_hour_cycles(String core_path, UnicodeLocaleData& locale_data)
  53. {
  54. // https://unicode.org/reports/tr35/tr35-dates.html#Time_Data
  55. LexicalPath time_data_path(move(core_path));
  56. time_data_path = time_data_path.append("supplemental"sv);
  57. time_data_path = time_data_path.append("timeData.json"sv);
  58. auto time_data_file = TRY(Core::File::open(time_data_path.string(), Core::OpenMode::ReadOnly));
  59. auto time_data = TRY(JsonValue::from_string(time_data_file->read_all()));
  60. auto const& supplemental_object = time_data.as_object().get("supplemental"sv);
  61. auto const& time_data_object = supplemental_object.as_object().get("timeData"sv);
  62. auto parse_hour_cycle = [](StringView hour_cycle) -> Optional<Unicode::HourCycle> {
  63. if (hour_cycle == "h"sv)
  64. return Unicode::HourCycle::H12;
  65. if (hour_cycle == "H"sv)
  66. return Unicode::HourCycle::H23;
  67. if (hour_cycle == "K"sv)
  68. return Unicode::HourCycle::H11;
  69. if (hour_cycle == "k"sv)
  70. return Unicode::HourCycle::H24;
  71. return {};
  72. };
  73. time_data_object.as_object().for_each_member([&](auto const& key, JsonValue const& value) {
  74. auto allowed_hour_cycles_string = value.as_object().get("_allowed"sv).as_string();
  75. auto allowed_hour_cycles = allowed_hour_cycles_string.split_view(' ');
  76. Vector<Unicode::HourCycle> hour_cycles;
  77. for (auto allowed_hour_cycle : allowed_hour_cycles) {
  78. if (auto hour_cycle = parse_hour_cycle(allowed_hour_cycle); hour_cycle.has_value())
  79. hour_cycles.append(*hour_cycle);
  80. }
  81. locale_data.hour_cycles.set(key, move(hour_cycles));
  82. if (!locale_data.hour_cycle_regions.contains_slow(key))
  83. locale_data.hour_cycle_regions.append(key);
  84. });
  85. return {};
  86. };
  87. static void parse_date_time_pattern(CalendarPattern& format, String pattern, UnicodeLocaleData& locale_data)
  88. {
  89. // FIXME: This is very incomplete. Similar to NumberFormat, the pattern string will need to be
  90. // parsed to fill in the CalendarPattern struct, and modified to be useable at runtime.
  91. // For now, this is enough to implement the DateTimeFormat constructor.
  92. //
  93. // https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
  94. format.pattern_index = locale_data.unique_strings.ensure(move(pattern));
  95. }
  96. static ErrorOr<void> parse_calendars(String locale_calendars_path, UnicodeLocaleData& locale_data, Locale& locale)
  97. {
  98. LexicalPath calendars_path(move(locale_calendars_path));
  99. if (!calendars_path.basename().starts_with("ca-"sv))
  100. return {};
  101. auto calendars_file = TRY(Core::File::open(calendars_path.string(), Core::OpenMode::ReadOnly));
  102. auto calendars = TRY(JsonValue::from_string(calendars_file->read_all()));
  103. auto const& main_object = calendars.as_object().get("main"sv);
  104. auto const& locale_object = main_object.as_object().get(calendars_path.parent().basename());
  105. auto const& dates_object = locale_object.as_object().get("dates"sv);
  106. auto const& calendars_object = dates_object.as_object().get("calendars"sv);
  107. auto ensure_calendar = [&](auto const& calendar) -> Calendar& {
  108. return locale.calendars.ensure(calendar, [&]() {
  109. auto calendar_index = locale_data.unique_strings.ensure(calendar);
  110. return Calendar { .calendar = calendar_index };
  111. });
  112. };
  113. auto parse_patterns = [&](auto& formats, auto const& patterns_object) {
  114. auto full_format = patterns_object.get("full"sv);
  115. parse_date_time_pattern(formats.full_format, full_format.as_string(), locale_data);
  116. auto long_format = patterns_object.get("long"sv);
  117. parse_date_time_pattern(formats.long_format, long_format.as_string(), locale_data);
  118. auto medium_format = patterns_object.get("medium"sv);
  119. parse_date_time_pattern(formats.medium_format, medium_format.as_string(), locale_data);
  120. auto short_format = patterns_object.get("short"sv);
  121. parse_date_time_pattern(formats.short_format, short_format.as_string(), locale_data);
  122. };
  123. calendars_object.as_object().for_each_member([&](auto const& calendar_name, JsonValue const& value) {
  124. // The generic calendar is not a supported Unicode calendar key, so skip it:
  125. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#unicode_calendar_keys
  126. if (calendar_name == "generic"sv)
  127. return;
  128. auto& calendar = ensure_calendar(calendar_name);
  129. if (!locale_data.calendars.contains_slow(calendar_name))
  130. locale_data.calendars.append(calendar_name);
  131. auto const& date_formats_object = value.as_object().get("dateFormats"sv);
  132. parse_patterns(calendar.date_formats, date_formats_object.as_object());
  133. auto const& time_formats_object = value.as_object().get("timeFormats"sv);
  134. parse_patterns(calendar.time_formats, time_formats_object.as_object());
  135. auto const& date_time_formats_object = value.as_object().get("dateTimeFormats"sv);
  136. parse_patterns(calendar.date_time_formats, date_time_formats_object.as_object());
  137. auto const& available_formats = date_time_formats_object.as_object().get("availableFormats"sv);
  138. available_formats.as_object().for_each_member([&](auto const&, JsonValue const& pattern) {
  139. CalendarPattern format {};
  140. parse_date_time_pattern(format, pattern.as_string(), locale_data);
  141. calendar.available_formats.append(move(format));
  142. });
  143. });
  144. return {};
  145. }
  146. static ErrorOr<void> parse_all_locales(String core_path, String dates_path, UnicodeLocaleData& locale_data)
  147. {
  148. TRY(parse_hour_cycles(move(core_path), locale_data));
  149. auto dates_iterator = TRY(path_to_dir_iterator(move(dates_path)));
  150. auto remove_variants_from_path = [&](String path) -> ErrorOr<String> {
  151. auto parsed_locale = TRY(CanonicalLanguageID<StringIndexType>::parse(locale_data.unique_strings, LexicalPath::basename(path)));
  152. StringBuilder builder;
  153. builder.append(locale_data.unique_strings.get(parsed_locale.language));
  154. if (auto script = locale_data.unique_strings.get(parsed_locale.script); !script.is_empty())
  155. builder.appendff("-{}", script);
  156. if (auto region = locale_data.unique_strings.get(parsed_locale.region); !region.is_empty())
  157. builder.appendff("-{}", region);
  158. return builder.build();
  159. };
  160. while (dates_iterator.has_next()) {
  161. auto dates_path = TRY(next_path_from_dir_iterator(dates_iterator));
  162. auto calendars_iterator = TRY(path_to_dir_iterator(dates_path, {}));
  163. auto language = TRY(remove_variants_from_path(dates_path));
  164. auto& locale = locale_data.locales.ensure(language);
  165. while (calendars_iterator.has_next()) {
  166. auto calendars_path = TRY(next_path_from_dir_iterator(calendars_iterator));
  167. TRY(parse_calendars(move(calendars_path), locale_data, locale));
  168. }
  169. }
  170. return {};
  171. }
  172. static String format_identifier(StringView owner, String identifier)
  173. {
  174. identifier = identifier.replace("-"sv, "_"sv, true);
  175. if (all_of(identifier, is_ascii_digit))
  176. return String::formatted("{}_{}", owner[0], identifier);
  177. if (is_ascii_lower_alpha(identifier[0]))
  178. return String::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  179. return identifier;
  180. }
  181. static void generate_unicode_locale_header(Core::File& file, UnicodeLocaleData& locale_data)
  182. {
  183. StringBuilder builder;
  184. SourceGenerator generator { builder };
  185. generator.append(R"~~~(
  186. #pragma once
  187. #include <AK/Optional.h>
  188. #include <AK/StringView.h>
  189. #include <LibUnicode/Forward.h>
  190. namespace Unicode {
  191. )~~~");
  192. generate_enum(generator, format_identifier, "Calendar"sv, {}, locale_data.calendars, locale_data.calendar_aliases);
  193. generate_enum(generator, format_identifier, "HourCycleRegion"sv, {}, locale_data.hour_cycle_regions);
  194. generator.append(R"~~~(
  195. namespace Detail {
  196. Optional<Calendar> calendar_from_string(StringView calendar);
  197. Optional<HourCycleRegion> hour_cycle_region_from_string(StringView hour_cycle_region);
  198. Vector<Unicode::HourCycle> get_regional_hour_cycles(StringView region);
  199. Optional<Unicode::CalendarFormat> get_calendar_date_format(StringView locale, StringView calendar);
  200. Optional<Unicode::CalendarFormat> get_calendar_time_format(StringView locale, StringView calendar);
  201. Optional<Unicode::CalendarFormat> get_calendar_date_time_format(StringView locale, StringView calendar);
  202. Vector<Unicode::CalendarPattern> get_calendar_available_formats(StringView locale, StringView calendar);
  203. }
  204. }
  205. )~~~");
  206. VERIFY(file.write(generator.as_string_view()));
  207. }
  208. static void generate_unicode_locale_implementation(Core::File& file, UnicodeLocaleData& locale_data)
  209. {
  210. StringBuilder builder;
  211. SourceGenerator generator { builder };
  212. generator.set("string_index_type"sv, s_string_index_type);
  213. generator.append(R"~~~(
  214. #include <AK/Array.h>
  215. #include <AK/BinarySearch.h>
  216. #include <LibUnicode/DateTimeFormat.h>
  217. #include <LibUnicode/Locale.h>
  218. #include <LibUnicode/UnicodeDateTimeFormat.h>
  219. namespace Unicode::Detail {
  220. )~~~");
  221. locale_data.unique_strings.generate(generator);
  222. generator.append(R"~~~(
  223. struct CalendarPattern {
  224. Unicode::CalendarPattern to_unicode_calendar_pattern() const {
  225. Unicode::CalendarPattern calendar_pattern {};
  226. calendar_pattern.pattern = s_string_list[pattern];
  227. return calendar_pattern;
  228. }
  229. @string_index_type@ pattern { 0 };
  230. };
  231. struct CalendarFormat {
  232. Unicode::CalendarFormat to_unicode_calendar_format() const {
  233. Unicode::CalendarFormat calendar_format {};
  234. calendar_format.full_format = full_format.to_unicode_calendar_pattern();
  235. calendar_format.long_format = long_format.to_unicode_calendar_pattern();
  236. calendar_format.medium_format = medium_format.to_unicode_calendar_pattern();
  237. calendar_format.short_format = short_format.to_unicode_calendar_pattern();
  238. return calendar_format;
  239. }
  240. CalendarPattern full_format {};
  241. CalendarPattern long_format {};
  242. CalendarPattern medium_format {};
  243. CalendarPattern short_format {};
  244. };
  245. struct CalendarData {
  246. @string_index_type@ calendar { 0 };
  247. CalendarFormat date_formats {};
  248. CalendarFormat time_formats {};
  249. CalendarFormat date_time_formats {};
  250. Span<CalendarPattern const> available_formats {};
  251. };
  252. )~~~");
  253. auto append_calendar_pattern = [&](auto const& calendar_pattern) {
  254. generator.set("pattern"sv, String::number(calendar_pattern.pattern_index));
  255. generator.append("{ @pattern@ },");
  256. };
  257. auto append_calendar_format = [&](auto const& calendar_format) {
  258. generator.append("{ ");
  259. append_calendar_pattern(calendar_format.full_format);
  260. generator.append(" ");
  261. append_calendar_pattern(calendar_format.long_format);
  262. generator.append(" ");
  263. append_calendar_pattern(calendar_format.medium_format);
  264. generator.append(" ");
  265. append_calendar_pattern(calendar_format.short_format);
  266. generator.append(" },");
  267. };
  268. auto append_calendars = [&](String name, auto const& calendars) {
  269. auto format_name = [&](StringView calendar_key) {
  270. return String::formatted("{}_{}_formats", name, calendar_key);
  271. };
  272. for (auto const& calendar_key : locale_data.calendars) {
  273. auto const& calendar = calendars.find(calendar_key)->value;
  274. generator.set("name", format_name(calendar_key));
  275. generator.set("size", String::number(calendar.available_formats.size()));
  276. generator.append(R"~~~(
  277. static constexpr Array<CalendarPattern, @size@> @name@ { {)~~~");
  278. for (auto const& format : calendar.available_formats) {
  279. generator.append("\n ");
  280. append_calendar_pattern(format);
  281. }
  282. generator.append(R"~~~(
  283. } };
  284. )~~~");
  285. }
  286. generator.set("name", name);
  287. generator.set("size", String::number(calendars.size()));
  288. generator.append(R"~~~(
  289. static constexpr Array<CalendarData, @size@> @name@ { {)~~~");
  290. for (auto const& calendar_key : locale_data.calendars) {
  291. auto const& calendar = calendars.find(calendar_key)->value;
  292. generator.set("name", format_name(calendar_key));
  293. generator.set("calendar"sv, String::number(calendar.calendar));
  294. generator.append(R"~~~(
  295. { @calendar@, )~~~");
  296. append_calendar_format(calendar.date_formats);
  297. generator.append(" ");
  298. append_calendar_format(calendar.time_formats);
  299. generator.append(" ");
  300. append_calendar_format(calendar.date_time_formats);
  301. generator.append(" @name@.span() },");
  302. }
  303. generator.append(R"~~~(
  304. } };
  305. )~~~");
  306. };
  307. auto append_hour_cycles = [&](String name, auto const& hour_cycle_region) {
  308. auto const& hour_cycles = locale_data.hour_cycles.find(hour_cycle_region)->value;
  309. generator.set("name", name);
  310. generator.set("size", String::number(hour_cycles.size()));
  311. generator.append(R"~~~(
  312. static constexpr Array<u8, @size@> @name@ { { )~~~");
  313. for (auto hour_cycle : hour_cycles) {
  314. generator.set("hour_cycle", String::number(static_cast<u8>(hour_cycle)));
  315. generator.append("@hour_cycle@, ");
  316. }
  317. generator.append("} };");
  318. };
  319. generate_mapping(generator, locale_data.locales, "CalendarData"sv, "s_calendars"sv, "s_calendars_{}", [&](auto const& name, auto const& value) { append_calendars(name, value.calendars); });
  320. 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); });
  321. auto append_from_string = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) {
  322. HashValueMap<String> hashes;
  323. hashes.ensure_capacity(values.size());
  324. for (auto const& value : values)
  325. hashes.set(value.hash(), format_identifier(enum_title, value));
  326. for (auto const& alias : aliases)
  327. hashes.set(alias.alias.hash(), format_identifier(enum_title, alias.alias));
  328. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes));
  329. };
  330. append_from_string("Calendar"sv, "calendar"sv, locale_data.calendars, locale_data.calendar_aliases);
  331. append_from_string("HourCycleRegion"sv, "hour_cycle_region"sv, locale_data.hour_cycle_regions);
  332. generator.append(R"~~~(
  333. Vector<Unicode::HourCycle> get_regional_hour_cycles(StringView region)
  334. {
  335. auto region_value = hour_cycle_region_from_string(region);
  336. if (!region_value.has_value())
  337. return {};
  338. auto region_index = to_underlying(*region_value);
  339. auto const& regional_hour_cycles = s_hour_cycles.at(region_index);
  340. Vector<Unicode::HourCycle> hour_cycles;
  341. hour_cycles.ensure_capacity(regional_hour_cycles.size());
  342. for (auto hour_cycle : regional_hour_cycles)
  343. hour_cycles.unchecked_append(static_cast<Unicode::HourCycle>(hour_cycle));
  344. return hour_cycles;
  345. }
  346. static CalendarData const* find_calendar_data(StringView locale, StringView calendar)
  347. {
  348. auto locale_value = locale_from_string(locale);
  349. if (!locale_value.has_value())
  350. return nullptr;
  351. auto calendar_value = calendar_from_string(calendar);
  352. if (!calendar_value.has_value())
  353. return nullptr;
  354. auto locale_index = to_underlying(*locale_value) - 1; // Subtract 1 because 0 == Locale::None.
  355. auto calendar_index = to_underlying(*calendar_value);
  356. auto const& calendars = s_calendars.at(locale_index);
  357. return &calendars[calendar_index];
  358. }
  359. Optional<Unicode::CalendarFormat> get_calendar_date_format(StringView locale, StringView calendar)
  360. {
  361. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  362. return data->date_formats.to_unicode_calendar_format();
  363. return {};
  364. }
  365. Optional<Unicode::CalendarFormat> get_calendar_time_format(StringView locale, StringView calendar)
  366. {
  367. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  368. return data->time_formats.to_unicode_calendar_format();
  369. return {};
  370. }
  371. Optional<Unicode::CalendarFormat> get_calendar_date_time_format(StringView locale, StringView calendar)
  372. {
  373. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr)
  374. return data->date_time_formats.to_unicode_calendar_format();
  375. return {};
  376. }
  377. Vector<Unicode::CalendarPattern> get_calendar_available_formats(StringView locale, StringView calendar)
  378. {
  379. Vector<Unicode::CalendarPattern> result {};
  380. if (auto const* data = find_calendar_data(locale, calendar); data != nullptr) {
  381. result.ensure_capacity(data->available_formats.size());
  382. for (auto const& format : data->available_formats)
  383. result.unchecked_append(format.to_unicode_calendar_pattern());
  384. }
  385. return result;
  386. }
  387. }
  388. )~~~");
  389. VERIFY(file.write(generator.as_string_view()));
  390. }
  391. ErrorOr<int> serenity_main(Main::Arguments arguments)
  392. {
  393. StringView generated_header_path;
  394. StringView generated_implementation_path;
  395. StringView core_path;
  396. StringView dates_path;
  397. Core::ArgsParser args_parser;
  398. args_parser.add_option(generated_header_path, "Path to the Unicode locale header file to generate", "generated-header-path", 'h', "generated-header-path");
  399. args_parser.add_option(generated_implementation_path, "Path to the Unicode locale implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  400. args_parser.add_option(core_path, "Path to cldr-core directory", "core-path", 'r', "core-path");
  401. args_parser.add_option(dates_path, "Path to cldr-dates directory", "dates-path", 'd', "dates-path");
  402. args_parser.parse(arguments);
  403. auto open_file = [&](StringView path) -> ErrorOr<NonnullRefPtr<Core::File>> {
  404. if (path.is_empty()) {
  405. args_parser.print_usage(stderr, arguments.argv[0]);
  406. return Error::from_string_literal("Must provide all command line options"sv);
  407. }
  408. return Core::File::open(path, Core::OpenMode::ReadWrite);
  409. };
  410. auto generated_header_file = TRY(open_file(generated_header_path));
  411. auto generated_implementation_file = TRY(open_file(generated_implementation_path));
  412. UnicodeLocaleData locale_data;
  413. TRY(parse_all_locales(core_path, dates_path, locale_data));
  414. generate_unicode_locale_header(generated_header_file, locale_data);
  415. generate_unicode_locale_implementation(generated_implementation_file, locale_data);
  416. return 0;
  417. }