GenerateTimeZoneData.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*
  2. * Copyright (c) 2022, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "../LibUnicode/GeneratorUtil.h" // FIXME: Move this somewhere common.
  7. #include <AK/Format.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/SourceGenerator.h>
  10. #include <AK/String.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Vector.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/File.h>
  15. namespace {
  16. using StringIndexType = u8;
  17. constexpr auto s_string_index_type = "u8"sv;
  18. struct DateTime {
  19. u16 year { 0 };
  20. Optional<u8> month;
  21. Optional<u8> day;
  22. Optional<u8> last_weekday;
  23. Optional<u8> after_weekday;
  24. Optional<u8> before_weekday;
  25. Optional<u8> hour;
  26. Optional<u8> minute;
  27. Optional<u8> second;
  28. };
  29. struct TimeZoneOffset {
  30. i64 offset { 0 };
  31. Optional<DateTime> until;
  32. Optional<String> dst_rule;
  33. Optional<i32> dst_rule_index;
  34. i64 dst_offset { 0 };
  35. StringIndexType standard_format { 0 };
  36. StringIndexType daylight_format { 0 };
  37. };
  38. struct DaylightSavingsOffset {
  39. i64 offset { 0 };
  40. u16 year_from { 0 };
  41. u16 year_to { 0 };
  42. DateTime in_effect;
  43. StringIndexType format { 0 };
  44. };
  45. struct TimeZoneData {
  46. UniqueStringStorage<StringIndexType> unique_strings;
  47. HashMap<String, Vector<TimeZoneOffset>> time_zones;
  48. Vector<String> time_zone_names;
  49. Vector<Alias> time_zone_aliases;
  50. HashMap<String, Vector<DaylightSavingsOffset>> dst_offsets;
  51. Vector<String> dst_offset_names;
  52. };
  53. }
  54. template<>
  55. struct AK::Formatter<DateTime> : Formatter<FormatString> {
  56. ErrorOr<void> format(FormatBuilder& builder, DateTime const& date_time)
  57. {
  58. return Formatter<FormatString>::format(builder,
  59. "{{ {}, {}, {}, {}, {}, {}, {}, {}, {} }}",
  60. date_time.year,
  61. date_time.month.value_or(1),
  62. date_time.day.value_or(1),
  63. date_time.last_weekday.value_or(0),
  64. date_time.after_weekday.value_or(0),
  65. date_time.before_weekday.value_or(0),
  66. date_time.hour.value_or(0),
  67. date_time.minute.value_or(0),
  68. date_time.second.value_or(0));
  69. }
  70. };
  71. template<>
  72. struct AK::Formatter<TimeZoneOffset> : Formatter<FormatString> {
  73. ErrorOr<void> format(FormatBuilder& builder, TimeZoneOffset const& time_zone_offset)
  74. {
  75. return Formatter<FormatString>::format(builder,
  76. "{{ {}, {}, {}, {}, {}, {}, {} }}",
  77. time_zone_offset.offset,
  78. time_zone_offset.until.value_or({}),
  79. time_zone_offset.until.has_value(),
  80. time_zone_offset.dst_rule_index.value_or(-1),
  81. time_zone_offset.dst_offset,
  82. time_zone_offset.standard_format,
  83. time_zone_offset.daylight_format);
  84. }
  85. };
  86. template<>
  87. struct AK::Formatter<DaylightSavingsOffset> : Formatter<FormatString> {
  88. ErrorOr<void> format(FormatBuilder& builder, DaylightSavingsOffset const& dst_offset)
  89. {
  90. return Formatter<FormatString>::format(builder,
  91. "{{ {}, {}, {}, {}, {} }}",
  92. dst_offset.offset,
  93. dst_offset.year_from,
  94. dst_offset.year_to,
  95. dst_offset.in_effect,
  96. dst_offset.format);
  97. }
  98. };
  99. static Optional<DateTime> parse_date_time(Span<StringView const> segments)
  100. {
  101. constexpr auto months = Array { "Jan"sv, "Feb"sv, "Mar"sv, "Apr"sv, "May"sv, "Jun"sv, "Jul"sv, "Aug"sv, "Sep"sv, "Oct"sv, "Nov"sv, "Dec"sv };
  102. constexpr auto weekdays = Array { "Sun"sv, "Mon"sv, "Tue"sv, "Wed"sv, "Thu"sv, "Fri"sv, "Sat"sv };
  103. auto comment_index = find_index(segments.begin(), segments.end(), "#"sv);
  104. if (comment_index != segments.size())
  105. segments = segments.slice(0, comment_index);
  106. if (segments.is_empty())
  107. return {};
  108. DateTime date_time {};
  109. date_time.year = segments[0].to_uint().value();
  110. if (segments.size() > 1)
  111. date_time.month = find_index(months.begin(), months.end(), segments[1]) + 1;
  112. if (segments.size() > 2) {
  113. if (segments[2].starts_with("last"sv)) {
  114. auto weekday = segments[2].substring_view("last"sv.length());
  115. date_time.last_weekday = find_index(weekdays.begin(), weekdays.end(), weekday);
  116. } else if (auto index = segments[2].find(">="sv); index.has_value()) {
  117. auto weekday = segments[2].substring_view(0, *index);
  118. date_time.after_weekday = find_index(weekdays.begin(), weekdays.end(), weekday);
  119. auto day = segments[2].substring_view(*index + ">="sv.length());
  120. date_time.day = day.to_uint().value();
  121. } else if (auto index = segments[2].find("<="sv); index.has_value()) {
  122. auto weekday = segments[2].substring_view(0, *index);
  123. date_time.before_weekday = find_index(weekdays.begin(), weekdays.end(), weekday);
  124. auto day = segments[2].substring_view(*index + "<="sv.length());
  125. date_time.day = day.to_uint().value();
  126. } else {
  127. date_time.day = segments[2].to_uint().value();
  128. }
  129. }
  130. if (segments.size() > 3) {
  131. // FIXME: Some times end with a letter, e.g. "2:00u" and "2:00s". Figure out what this means and handle it.
  132. auto time_segments = segments[3].split_view(':');
  133. date_time.hour = time_segments[0].to_int().value();
  134. date_time.minute = time_segments.size() > 1 ? time_segments[1].substring_view(0, 2).to_uint().value() : 0;
  135. date_time.second = time_segments.size() > 2 ? time_segments[2].substring_view(0, 2).to_uint().value() : 0;
  136. }
  137. return date_time;
  138. }
  139. static i64 parse_time_offset(StringView segment)
  140. {
  141. auto segments = segment.split_view(':');
  142. i64 hours = segments[0].to_int().value();
  143. i64 minutes = segments.size() > 1 ? segments[1].to_uint().value() : 0;
  144. i64 seconds = segments.size() > 2 ? segments[2].to_uint().value() : 0;
  145. i64 sign = ((hours < 0) || (segments[0] == "-0"sv)) ? -1 : 1;
  146. return (hours * 3600) + sign * ((minutes * 60) + seconds);
  147. }
  148. static void parse_dst_rule(StringView segment, TimeZoneOffset& time_zone)
  149. {
  150. if (segment.contains(':'))
  151. time_zone.dst_offset = parse_time_offset(segment);
  152. else if (segment != "-"sv)
  153. time_zone.dst_rule = segment;
  154. }
  155. static void parse_format(StringView format, TimeZoneData& time_zone_data, TimeZoneOffset& time_zone)
  156. {
  157. auto formats = format.replace("%s"sv, "{}"sv).split('/');
  158. VERIFY(formats.size() <= 2);
  159. time_zone.standard_format = time_zone_data.unique_strings.ensure(formats[0]);
  160. if (formats.size() == 2)
  161. time_zone.daylight_format = time_zone_data.unique_strings.ensure(formats[1]);
  162. else
  163. time_zone.daylight_format = time_zone.standard_format;
  164. }
  165. static Vector<TimeZoneOffset>& parse_zone(StringView zone_line, TimeZoneData& time_zone_data)
  166. {
  167. auto segments = zone_line.split_view_if([](char ch) { return (ch == '\t') || (ch == ' '); });
  168. // "Zone" NAME STDOFF RULES FORMAT [UNTIL]
  169. VERIFY(segments[0] == "Zone"sv);
  170. auto name = segments[1];
  171. TimeZoneOffset time_zone {};
  172. time_zone.offset = parse_time_offset(segments[2]);
  173. parse_dst_rule(segments[3], time_zone);
  174. parse_format(segments[4], time_zone_data, time_zone);
  175. if (segments.size() > 5)
  176. time_zone.until = parse_date_time(segments.span().slice(5));
  177. auto& time_zones = time_zone_data.time_zones.ensure(name);
  178. time_zones.append(move(time_zone));
  179. if (!time_zone_data.time_zone_names.contains_slow(name))
  180. time_zone_data.time_zone_names.append(name);
  181. return time_zones;
  182. }
  183. static void parse_zone_continuation(StringView zone_line, TimeZoneData& time_zone_data, Vector<TimeZoneOffset>& time_zones)
  184. {
  185. auto segments = zone_line.split_view_if([](char ch) { return (ch == '\t') || (ch == ' '); });
  186. // STDOFF RULES FORMAT [UNTIL]
  187. TimeZoneOffset time_zone {};
  188. time_zone.offset = parse_time_offset(segments[0]);
  189. parse_dst_rule(segments[1], time_zone);
  190. parse_format(segments[2], time_zone_data, time_zone);
  191. if (segments.size() > 3)
  192. time_zone.until = parse_date_time(segments.span().slice(3));
  193. time_zones.append(move(time_zone));
  194. }
  195. static void parse_link(StringView link_line, TimeZoneData& time_zone_data)
  196. {
  197. auto segments = link_line.split_view_if([](char ch) { return (ch == '\t') || (ch == ' '); });
  198. // Link TARGET LINK-NAME
  199. VERIFY(segments[0] == "Link"sv);
  200. auto target = segments[1];
  201. auto alias = segments[2];
  202. time_zone_data.time_zone_aliases.append({ target, alias });
  203. }
  204. static void parse_rule(StringView rule_line, TimeZoneData& time_zone_data)
  205. {
  206. auto segments = rule_line.split_view_if([](char ch) { return (ch == '\t') || (ch == ' '); });
  207. // Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S
  208. VERIFY(segments[0] == "Rule"sv);
  209. auto name = segments[1];
  210. DaylightSavingsOffset dst_offset {};
  211. dst_offset.offset = parse_time_offset(segments[8]);
  212. dst_offset.year_from = segments[2].to_uint().value();
  213. if (segments[3] == "only")
  214. dst_offset.year_to = dst_offset.year_from;
  215. else if (segments[3] == "max"sv)
  216. dst_offset.year_to = NumericLimits<u16>::max();
  217. else
  218. dst_offset.year_to = segments[3].to_uint().value();
  219. auto in_effect = Array { "0"sv, segments[5], segments[6], segments[7] };
  220. dst_offset.in_effect = parse_date_time(in_effect).release_value();
  221. if (segments[9] != "-"sv)
  222. dst_offset.format = time_zone_data.unique_strings.ensure(segments[9]);
  223. auto& dst_offsets = time_zone_data.dst_offsets.ensure(name);
  224. dst_offsets.append(move(dst_offset));
  225. if (!time_zone_data.dst_offset_names.contains_slow(name))
  226. time_zone_data.dst_offset_names.append(name);
  227. }
  228. static ErrorOr<void> parse_time_zones(StringView time_zone_path, TimeZoneData& time_zone_data)
  229. {
  230. // For reference, the man page for `zic` has the best documentation of the TZDB file format.
  231. auto file = TRY(Core::File::open(time_zone_path, Core::OpenMode::ReadOnly));
  232. Vector<TimeZoneOffset>* last_parsed_zone = nullptr;
  233. while (file->can_read_line()) {
  234. auto line = file->read_line();
  235. if (line.is_empty() || line.trim_whitespace(TrimMode::Left).starts_with('#'))
  236. continue;
  237. if (line.starts_with("Zone"sv)) {
  238. last_parsed_zone = &parse_zone(line, time_zone_data);
  239. } else if (line.starts_with('\t')) {
  240. VERIFY(last_parsed_zone != nullptr);
  241. parse_zone_continuation(line, time_zone_data, *last_parsed_zone);
  242. } else {
  243. last_parsed_zone = nullptr;
  244. if (line.starts_with("Link"sv))
  245. parse_link(line, time_zone_data);
  246. else if (line.starts_with("Rule"sv))
  247. parse_rule(line, time_zone_data);
  248. }
  249. }
  250. return {};
  251. }
  252. static void set_dst_rule_indices(TimeZoneData& time_zone_data)
  253. {
  254. for (auto& time_zone : time_zone_data.time_zones) {
  255. for (auto& time_zone_offset : time_zone.value) {
  256. if (!time_zone_offset.dst_rule.has_value())
  257. continue;
  258. auto dst_rule_index = time_zone_data.dst_offset_names.find_first_index(*time_zone_offset.dst_rule);
  259. time_zone_offset.dst_rule_index = static_cast<i32>(dst_rule_index.value());
  260. }
  261. }
  262. }
  263. static String format_identifier(StringView owner, String identifier)
  264. {
  265. constexpr auto gmt_time_zones = Array { "Etc/GMT"sv, "GMT"sv };
  266. for (auto gmt_time_zone : gmt_time_zones) {
  267. if (identifier.starts_with(gmt_time_zone)) {
  268. auto offset = identifier.substring_view(gmt_time_zone.length());
  269. if (offset.starts_with('+'))
  270. identifier = String::formatted("{}_Ahead_{}", gmt_time_zone, offset.substring_view(1));
  271. else if (offset.starts_with('-'))
  272. identifier = String::formatted("{}_Behind_{}", gmt_time_zone, offset.substring_view(1));
  273. }
  274. }
  275. identifier = identifier.replace("-"sv, "_"sv, true);
  276. identifier = identifier.replace("/"sv, "_"sv, true);
  277. if (all_of(identifier, is_ascii_digit))
  278. return String::formatted("{}_{}", owner[0], identifier);
  279. if (is_ascii_lower_alpha(identifier[0]))
  280. return String::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  281. return identifier;
  282. }
  283. static void generate_time_zone_data_header(Core::File& file, TimeZoneData& time_zone_data)
  284. {
  285. StringBuilder builder;
  286. SourceGenerator generator { builder };
  287. generator.append(R"~~~(
  288. #pragma once
  289. #include <AK/Types.h>
  290. namespace TimeZone {
  291. )~~~");
  292. generate_enum(generator, format_identifier, "TimeZone"sv, {}, time_zone_data.time_zone_names, time_zone_data.time_zone_aliases);
  293. generate_enum(generator, format_identifier, "DaylightSavingsRule"sv, {}, time_zone_data.dst_offset_names);
  294. generator.append(R"~~~(
  295. }
  296. )~~~");
  297. VERIFY(file.write(generator.as_string_view()));
  298. }
  299. static void generate_time_zone_data_implementation(Core::File& file, TimeZoneData& time_zone_data)
  300. {
  301. StringBuilder builder;
  302. SourceGenerator generator { builder };
  303. generator.set("string_index_type"sv, s_string_index_type);
  304. set_dst_rule_indices(time_zone_data);
  305. generator.append(R"~~~(
  306. #include <AK/Array.h>
  307. #include <AK/BinarySearch.h>
  308. #include <AK/Optional.h>
  309. #include <AK/Span.h>
  310. #include <AK/StringView.h>
  311. #include <AK/Time.h>
  312. #include <LibTimeZone/TimeZone.h>
  313. #include <LibTimeZone/TimeZoneData.h>
  314. namespace TimeZone {
  315. struct DateTime {
  316. AK::Time time_since_epoch() const
  317. {
  318. // FIXME: This implementation does not take last_weekday, after_weekday, or before_weekday into account.
  319. return AK::Time::from_timestamp(year, month, day, hour, minute, second, 0);
  320. }
  321. u16 year { 0 };
  322. u8 month { 1 };
  323. u8 day { 1 };
  324. u8 last_weekday { 0 };
  325. u8 after_weekday { 0 };
  326. u8 before_weekday { 0 };
  327. u8 hour { 0 };
  328. u8 minute { 0 };
  329. u8 second { 0 };
  330. };
  331. struct TimeZoneOffset {
  332. i64 offset { 0 };
  333. DateTime until {};
  334. bool has_until { false };
  335. i32 dst_rule { -1 };
  336. i64 dst_offset { 0 };
  337. @string_index_type@ standard_format { 0 };
  338. @string_index_type@ daylight_format { 0 };
  339. };
  340. struct DaylightSavingsOffset {
  341. AK::Time time_in_effect(AK::Time time) const
  342. {
  343. auto in_effect = this->in_effect;
  344. in_effect.year = seconds_since_epoch_to_year(time.to_seconds());
  345. return in_effect.time_since_epoch();
  346. }
  347. i64 offset { 0 };
  348. u16 year_from { 0 };
  349. u16 year_to { 0 };
  350. DateTime in_effect {};
  351. @string_index_type@ format { 0 };
  352. };
  353. )~~~");
  354. time_zone_data.unique_strings.generate(generator);
  355. auto append_offsets = [&](auto const& name, auto type, auto const& offsets) {
  356. generator.set("name", name);
  357. generator.set("type", type);
  358. generator.set("size", String::number(offsets.size()));
  359. generator.append(R"~~~(
  360. static constexpr Array<@type@, @size@> @name@ { {
  361. )~~~");
  362. for (auto const& offset : offsets)
  363. generator.append(String::formatted(" {},\n", offset));
  364. generator.append("} };\n");
  365. };
  366. generate_mapping(generator, time_zone_data.time_zone_names, "TimeZoneOffset"sv, "s_time_zone_offsets"sv, "s_time_zone_offsets_{}", format_identifier,
  367. [&](auto const& name, auto const& value) {
  368. auto const& time_zone_offsets = time_zone_data.time_zones.find(value)->value;
  369. append_offsets(name, "TimeZoneOffset"sv, time_zone_offsets);
  370. });
  371. generate_mapping(generator, time_zone_data.dst_offset_names, "DaylightSavingsOffset"sv, "s_dst_offsets"sv, "s_dst_offsets_{}", format_identifier,
  372. [&](auto const& name, auto const& value) {
  373. auto const& dst_offsets = time_zone_data.dst_offsets.find(value)->value;
  374. append_offsets(name, "DaylightSavingsOffset"sv, dst_offsets);
  375. });
  376. auto append_string_conversions = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) {
  377. HashValueMap<String> hashes;
  378. hashes.ensure_capacity(values.size());
  379. auto hash = [](auto const& value) {
  380. return CaseInsensitiveStringViewTraits::hash(value);
  381. };
  382. for (auto const& value : values)
  383. hashes.set(hash(value), format_identifier(enum_title, value));
  384. for (auto const& alias : aliases)
  385. hashes.set(hash(alias.alias), format_identifier(enum_title, alias.alias));
  386. ValueFromStringOptions options {};
  387. options.sensitivity = CaseSensitivity::CaseInsensitive;
  388. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes), options);
  389. generate_value_to_string(generator, "{}_to_string"sv, enum_title, enum_snake, format_identifier, values);
  390. };
  391. append_string_conversions("TimeZone"sv, "time_zone"sv, time_zone_data.time_zone_names, time_zone_data.time_zone_aliases);
  392. append_string_conversions("DaylightSavingsRule"sv, "daylight_savings_rule"sv, time_zone_data.dst_offset_names);
  393. generator.append(R"~~~(
  394. static Array<DaylightSavingsOffset const*, 2> find_dst_offsets(TimeZoneOffset const& time_zone_offset, AK::Time time)
  395. {
  396. auto const& dst_rules = s_dst_offsets[time_zone_offset.dst_rule];
  397. DaylightSavingsOffset const* standard_offset = nullptr;
  398. DaylightSavingsOffset const* daylight_offset = nullptr;
  399. auto preferred_rule = [&](auto* current_offset, auto& new_offset) {
  400. if (!current_offset)
  401. return &new_offset;
  402. auto new_time_in_effect = new_offset.time_in_effect(time);
  403. return (time >= new_time_in_effect) ? &new_offset : current_offset;
  404. };
  405. for (size_t index = 0; (index < dst_rules.size()) && (!standard_offset || !daylight_offset); ++index) {
  406. auto const& dst_rule = dst_rules[index];
  407. auto year_from = AK::Time::from_timestamp(dst_rule.year_from, 1, 1, 0, 0, 0, 0);
  408. auto year_to = AK::Time::from_timestamp(dst_rule.year_to + 1, 1, 1, 0, 0, 0, 0);
  409. if ((time < year_from) || (time >= year_to))
  410. continue;
  411. if (dst_rule.offset == 0)
  412. standard_offset = preferred_rule(standard_offset, dst_rule);
  413. else
  414. daylight_offset = preferred_rule(daylight_offset, dst_rule);
  415. }
  416. // In modern times, there will always be a standard rule in the TZDB, but that isn't true in
  417. // all time zones in or before the early 1900s. For example, the "US" rules begin in 1918.
  418. if (!standard_offset) {
  419. static DaylightSavingsOffset const empty_offset {};
  420. return { &empty_offset, &empty_offset };
  421. }
  422. return { standard_offset, daylight_offset ? daylight_offset : standard_offset };
  423. }
  424. static Offset get_active_dst_offset(TimeZoneOffset const& time_zone_offset, AK::Time time)
  425. {
  426. auto offsets = find_dst_offsets(time_zone_offset, time);
  427. if (offsets[0] == offsets[1])
  428. return { offsets[0]->offset, InDST::No };
  429. auto standard_time_in_effect = offsets[0]->time_in_effect(time);
  430. auto daylight_time_in_effect = offsets[1]->time_in_effect(time);
  431. if (daylight_time_in_effect < standard_time_in_effect) {
  432. if ((time < daylight_time_in_effect) || (time >= standard_time_in_effect))
  433. return { offsets[0]->offset, InDST::No };
  434. } else {
  435. if ((time >= standard_time_in_effect) && (time < daylight_time_in_effect))
  436. return { offsets[0]->offset, InDST::No };
  437. }
  438. return { offsets[1]->offset, InDST::Yes };
  439. }
  440. static TimeZoneOffset const& find_time_zone_offset(TimeZone time_zone, AK::Time time)
  441. {
  442. auto const& time_zone_offsets = s_time_zone_offsets[to_underlying(time_zone)];
  443. size_t index = 0;
  444. for (; index < time_zone_offsets.size(); ++index) {
  445. auto const& time_zone_offset = time_zone_offsets[index];
  446. if (!time_zone_offset.has_until || (time_zone_offset.until.time_since_epoch() > time))
  447. break;
  448. }
  449. VERIFY(index < time_zone_offsets.size());
  450. return time_zone_offsets[index];
  451. }
  452. Optional<Offset> get_time_zone_offset(TimeZone time_zone, AK::Time time)
  453. {
  454. auto const& time_zone_offset = find_time_zone_offset(time_zone, time);
  455. Offset dst_offset {};
  456. if (time_zone_offset.dst_rule != -1) {
  457. dst_offset = get_active_dst_offset(time_zone_offset, time);
  458. } else {
  459. auto in_dst = time_zone_offset.dst_offset == 0 ? InDST::No : InDST::Yes;
  460. dst_offset = { time_zone_offset.dst_offset, in_dst };
  461. }
  462. dst_offset.seconds += time_zone_offset.offset;
  463. return dst_offset;
  464. }
  465. Optional<Array<NamedOffset, 2>> get_named_time_zone_offsets(TimeZone time_zone, AK::Time time)
  466. {
  467. auto const& time_zone_offset = find_time_zone_offset(time_zone, time);
  468. Array<NamedOffset, 2> named_offsets;
  469. auto format_name = [](auto format, auto offset) -> String {
  470. if (offset == 0)
  471. return s_string_list[format].replace("{}"sv, ""sv);
  472. return String::formatted(s_string_list[format], s_string_list[offset]);
  473. };
  474. auto set_named_offset = [&](auto& named_offset, auto dst_offset, auto in_dst, auto format, auto offset) {
  475. named_offset.seconds = time_zone_offset.offset + dst_offset;
  476. named_offset.in_dst = in_dst;
  477. named_offset.name = format_name(format, offset);
  478. };
  479. if (time_zone_offset.dst_rule != -1) {
  480. auto offsets = find_dst_offsets(time_zone_offset, time);
  481. auto in_dst = offsets[1]->offset == 0 ? InDST::No : InDST::Yes;
  482. set_named_offset(named_offsets[0], offsets[0]->offset, InDST::No, time_zone_offset.standard_format, offsets[0]->format);
  483. set_named_offset(named_offsets[1], offsets[1]->offset, in_dst, time_zone_offset.daylight_format, offsets[1]->format);
  484. } else {
  485. auto in_dst = time_zone_offset.dst_offset == 0 ? InDST::No : InDST::Yes;
  486. set_named_offset(named_offsets[0], time_zone_offset.dst_offset, in_dst, time_zone_offset.standard_format, 0);
  487. set_named_offset(named_offsets[1], time_zone_offset.dst_offset, in_dst, time_zone_offset.daylight_format, 0);
  488. }
  489. return named_offsets;
  490. }
  491. Span<StringView const> all_time_zones()
  492. {
  493. static constexpr auto all_time_zones = Array {
  494. )~~~");
  495. for (auto const& time_zone : time_zone_data.time_zone_names) {
  496. generator.set("time_zone", time_zone);
  497. generator.append("\"@time_zone@\"sv, ");
  498. }
  499. generator.append(R"~~~(
  500. };
  501. return all_time_zones;
  502. }
  503. }
  504. )~~~");
  505. VERIFY(file.write(generator.as_string_view()));
  506. }
  507. ErrorOr<int> serenity_main(Main::Arguments arguments)
  508. {
  509. StringView generated_header_path;
  510. StringView generated_implementation_path;
  511. Vector<StringView> time_zone_paths;
  512. Core::ArgsParser args_parser;
  513. args_parser.add_option(generated_header_path, "Path to the time zone data header file to generate", "generated-header-path", 'h', "generated-header-path");
  514. args_parser.add_option(generated_implementation_path, "Path to the time zone data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  515. args_parser.add_positional_argument(time_zone_paths, "Paths to the time zone database files", "time-zone-paths");
  516. args_parser.parse(arguments);
  517. auto open_file = [&](StringView path) -> ErrorOr<NonnullRefPtr<Core::File>> {
  518. if (path.is_empty()) {
  519. args_parser.print_usage(stderr, arguments.argv[0]);
  520. return Error::from_string_literal("Must provide all command line options"sv);
  521. }
  522. return Core::File::open(path, Core::OpenMode::ReadWrite);
  523. };
  524. auto generated_header_file = TRY(open_file(generated_header_path));
  525. auto generated_implementation_file = TRY(open_file(generated_implementation_path));
  526. TimeZoneData time_zone_data {};
  527. for (auto time_zone_path : time_zone_paths)
  528. TRY(parse_time_zones(time_zone_path, time_zone_data));
  529. generate_time_zone_data_header(generated_header_file, time_zone_data);
  530. generate_time_zone_data_implementation(generated_implementation_file, time_zone_data);
  531. return 0;
  532. }