GenerateUnicodeDateTimeFormat.cpp 19 KB

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