GenerateTimeZoneData.cpp 27 KB

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