GenerateTimeZoneData.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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, ReplaceMode::FirstOnly).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 line = TRY(file->read_line(buffer));
  258. if (line.is_empty() || line.trim_whitespace(TrimMode::Left).starts_with('#'))
  259. continue;
  260. if (line.starts_with("Zone"sv)) {
  261. last_parsed_zone = &parse_zone(line, time_zone_data);
  262. } else if (line.starts_with('\t')) {
  263. VERIFY(last_parsed_zone != nullptr);
  264. parse_zone_continuation(line, time_zone_data, *last_parsed_zone);
  265. } else {
  266. last_parsed_zone = nullptr;
  267. if (line.starts_with("Link"sv))
  268. parse_link(line, time_zone_data);
  269. else if (line.starts_with("Rule"sv))
  270. parse_rule(line, time_zone_data);
  271. }
  272. }
  273. return {};
  274. }
  275. static ErrorOr<void> parse_time_zone_coordinates(Core::Stream::BufferedFile& file, TimeZoneData& time_zone_data)
  276. {
  277. auto parse_coordinate = [](auto coordinate) {
  278. VERIFY(coordinate.substring_view(0, 1).is_one_of("+"sv, "-"sv));
  279. TimeZone::Coordinate parsed {};
  280. if (coordinate.length() == 5) {
  281. // ±DDMM
  282. parsed.degrees = coordinate.substring_view(0, 3).to_int().value();
  283. parsed.minutes = coordinate.substring_view(3).to_int().value();
  284. } else if (coordinate.length() == 6) {
  285. // ±DDDMM
  286. parsed.degrees = coordinate.substring_view(0, 4).to_int().value();
  287. parsed.minutes = coordinate.substring_view(4).to_int().value();
  288. } else if (coordinate.length() == 7) {
  289. // ±DDMMSS
  290. parsed.degrees = coordinate.substring_view(0, 3).to_int().value();
  291. parsed.minutes = coordinate.substring_view(3, 2).to_int().value();
  292. parsed.seconds = coordinate.substring_view(5).to_int().value();
  293. } else if (coordinate.length() == 8) {
  294. // ±DDDDMMSS
  295. parsed.degrees = coordinate.substring_view(0, 4).to_int().value();
  296. parsed.minutes = coordinate.substring_view(4, 2).to_int().value();
  297. parsed.seconds = coordinate.substring_view(6).to_int().value();
  298. } else {
  299. VERIFY_NOT_REACHED();
  300. }
  301. return parsed;
  302. };
  303. Array<u8, 1024> buffer {};
  304. while (TRY(file.can_read_line())) {
  305. auto line = TRY(file.read_line(buffer));
  306. if (line.is_empty() || line.trim_whitespace(TrimMode::Left).starts_with('#'))
  307. continue;
  308. auto segments = line.split_view('\t');
  309. auto coordinates = segments[1];
  310. auto zone = segments[2];
  311. VERIFY(time_zone_data.time_zones.contains(zone));
  312. auto index = coordinates.find_any_of("+-"sv, StringView::SearchDirection::Backward).value();
  313. auto latitude = parse_coordinate(coordinates.substring_view(0, index));
  314. auto longitude = parse_coordinate(coordinates.substring_view(index));
  315. time_zone_data.time_zone_coordinates.set(zone, { latitude, longitude });
  316. }
  317. return {};
  318. }
  319. static void set_dst_rule_indices(TimeZoneData& time_zone_data)
  320. {
  321. for (auto& time_zone : time_zone_data.time_zones) {
  322. for (auto& time_zone_offset : time_zone.value) {
  323. if (!time_zone_offset.dst_rule.has_value())
  324. continue;
  325. auto dst_rule_index = time_zone_data.dst_offset_names.find_first_index(*time_zone_offset.dst_rule);
  326. time_zone_offset.dst_rule_index = static_cast<i32>(dst_rule_index.value());
  327. }
  328. }
  329. }
  330. static String format_identifier(StringView owner, String identifier)
  331. {
  332. constexpr auto gmt_time_zones = Array { "Etc/GMT"sv, "GMT"sv };
  333. for (auto gmt_time_zone : gmt_time_zones) {
  334. if (identifier.starts_with(gmt_time_zone)) {
  335. auto offset = identifier.substring_view(gmt_time_zone.length());
  336. if (offset.starts_with('+'))
  337. identifier = String::formatted("{}_Ahead_{}", gmt_time_zone, offset.substring_view(1));
  338. else if (offset.starts_with('-'))
  339. identifier = String::formatted("{}_Behind_{}", gmt_time_zone, offset.substring_view(1));
  340. }
  341. }
  342. identifier = identifier.replace("-"sv, "_"sv, ReplaceMode::All);
  343. identifier = identifier.replace("/"sv, "_"sv, ReplaceMode::All);
  344. if (all_of(identifier, is_ascii_digit))
  345. return String::formatted("{}_{}", owner[0], identifier);
  346. if (is_ascii_lower_alpha(identifier[0]))
  347. return String::formatted("{:c}{}", to_ascii_uppercase(identifier[0]), identifier.substring_view(1));
  348. return identifier;
  349. }
  350. static ErrorOr<void> generate_time_zone_data_header(Core::Stream::BufferedFile& file, TimeZoneData& time_zone_data)
  351. {
  352. StringBuilder builder;
  353. SourceGenerator generator { builder };
  354. generator.append(R"~~~(
  355. #pragma once
  356. #include <AK/Types.h>
  357. namespace TimeZone {
  358. )~~~");
  359. generate_enum(generator, format_identifier, "TimeZone"sv, {}, time_zone_data.time_zone_names, time_zone_data.time_zone_aliases);
  360. generate_enum(generator, format_identifier, "DaylightSavingsRule"sv, {}, time_zone_data.dst_offset_names);
  361. generator.append(R"~~~(
  362. }
  363. )~~~");
  364. TRY(file.write(generator.as_string_view().bytes()));
  365. return {};
  366. }
  367. static ErrorOr<void> generate_time_zone_data_implementation(Core::Stream::BufferedFile& file, TimeZoneData& time_zone_data)
  368. {
  369. StringBuilder builder;
  370. SourceGenerator generator { builder };
  371. generator.set("string_index_type"sv, s_string_index_type);
  372. set_dst_rule_indices(time_zone_data);
  373. generator.append(R"~~~(
  374. #include <AK/Array.h>
  375. #include <AK/BinarySearch.h>
  376. #include <AK/Optional.h>
  377. #include <AK/Span.h>
  378. #include <AK/StringView.h>
  379. #include <AK/Time.h>
  380. #include <LibTimeZone/TimeZone.h>
  381. #include <LibTimeZone/TimeZoneData.h>
  382. namespace TimeZone {
  383. struct DateTime {
  384. AK::Time time_since_epoch() const
  385. {
  386. // FIXME: This implementation does not take last_weekday, after_weekday, or before_weekday into account.
  387. return AK::Time::from_timestamp(year, month, day, hour, minute, second, 0);
  388. }
  389. u16 year { 0 };
  390. u8 month { 1 };
  391. u8 day { 1 };
  392. u8 last_weekday { 0 };
  393. u8 after_weekday { 0 };
  394. u8 before_weekday { 0 };
  395. u8 hour { 0 };
  396. u8 minute { 0 };
  397. u8 second { 0 };
  398. };
  399. struct TimeZoneOffset {
  400. i64 offset { 0 };
  401. DateTime until {};
  402. bool has_until { false };
  403. i32 dst_rule { -1 };
  404. i64 dst_offset { 0 };
  405. @string_index_type@ standard_format { 0 };
  406. @string_index_type@ daylight_format { 0 };
  407. };
  408. struct DaylightSavingsOffset {
  409. AK::Time time_in_effect(AK::Time time) const
  410. {
  411. auto in_effect = this->in_effect;
  412. in_effect.year = seconds_since_epoch_to_year(time.to_seconds());
  413. return in_effect.time_since_epoch();
  414. }
  415. i64 offset { 0 };
  416. u16 year_from { 0 };
  417. u16 year_to { 0 };
  418. DateTime in_effect {};
  419. @string_index_type@ format { 0 };
  420. };
  421. )~~~");
  422. time_zone_data.unique_strings.generate(generator);
  423. auto append_offsets = [&](auto const& name, auto type, auto const& offsets) {
  424. generator.set("name", name);
  425. generator.set("type", type);
  426. generator.set("size", String::number(offsets.size()));
  427. generator.append(R"~~~(
  428. static constexpr Array<@type@, @size@> @name@ { {
  429. )~~~");
  430. for (auto const& offset : offsets)
  431. generator.append(String::formatted(" {},\n", offset));
  432. generator.append("} };\n");
  433. };
  434. generate_mapping(generator, time_zone_data.time_zone_names, "TimeZoneOffset"sv, "s_time_zone_offsets"sv, "s_time_zone_offsets_{}", format_identifier,
  435. [&](auto const& name, auto const& value) {
  436. auto const& time_zone_offsets = time_zone_data.time_zones.find(value)->value;
  437. append_offsets(name, "TimeZoneOffset"sv, time_zone_offsets);
  438. });
  439. generate_mapping(generator, time_zone_data.dst_offset_names, "DaylightSavingsOffset"sv, "s_dst_offsets"sv, "s_dst_offsets_{}", format_identifier,
  440. [&](auto const& name, auto const& value) {
  441. auto const& dst_offsets = time_zone_data.dst_offsets.find(value)->value;
  442. append_offsets(name, "DaylightSavingsOffset"sv, dst_offsets);
  443. });
  444. generator.set("size", String::number(time_zone_data.time_zone_names.size()));
  445. generator.append(R"~~~(
  446. static constexpr Array<Location, @size@> s_time_zone_locations { {
  447. )~~~");
  448. for (auto const& time_zone : time_zone_data.time_zone_names) {
  449. auto location = time_zone_data.time_zone_coordinates.get(time_zone).value_or({});
  450. generator.append(String::formatted(" {},\n", location));
  451. }
  452. generator.append("} };\n");
  453. auto append_string_conversions = [&](StringView enum_title, StringView enum_snake, auto const& values, Vector<Alias> const& aliases = {}) {
  454. HashValueMap<String> hashes;
  455. hashes.ensure_capacity(values.size());
  456. auto hash = [](auto const& value) {
  457. return CaseInsensitiveStringViewTraits::hash(value);
  458. };
  459. for (auto const& value : values)
  460. hashes.set(hash(value), format_identifier(enum_title, value));
  461. for (auto const& alias : aliases)
  462. hashes.set(hash(alias.alias), format_identifier(enum_title, alias.alias));
  463. ValueFromStringOptions options {};
  464. options.sensitivity = CaseSensitivity::CaseInsensitive;
  465. generate_value_from_string(generator, "{}_from_string"sv, enum_title, enum_snake, move(hashes), options);
  466. generate_value_to_string(generator, "{}_to_string"sv, enum_title, enum_snake, format_identifier, values);
  467. };
  468. append_string_conversions("TimeZone"sv, "time_zone"sv, time_zone_data.time_zone_names, time_zone_data.time_zone_aliases);
  469. append_string_conversions("DaylightSavingsRule"sv, "daylight_savings_rule"sv, time_zone_data.dst_offset_names);
  470. generator.append(R"~~~(
  471. static Array<DaylightSavingsOffset const*, 2> find_dst_offsets(TimeZoneOffset const& time_zone_offset, AK::Time time)
  472. {
  473. auto const& dst_rules = s_dst_offsets[time_zone_offset.dst_rule];
  474. DaylightSavingsOffset const* standard_offset = nullptr;
  475. DaylightSavingsOffset const* daylight_offset = nullptr;
  476. auto preferred_rule = [&](auto* current_offset, auto& new_offset) {
  477. if (!current_offset)
  478. return &new_offset;
  479. auto new_time_in_effect = new_offset.time_in_effect(time);
  480. return (time >= new_time_in_effect) ? &new_offset : current_offset;
  481. };
  482. for (size_t index = 0; (index < dst_rules.size()) && (!standard_offset || !daylight_offset); ++index) {
  483. auto const& dst_rule = dst_rules[index];
  484. auto year_from = AK::Time::from_timestamp(dst_rule.year_from, 1, 1, 0, 0, 0, 0);
  485. auto year_to = AK::Time::from_timestamp(dst_rule.year_to + 1, 1, 1, 0, 0, 0, 0);
  486. if ((time < year_from) || (time >= year_to))
  487. continue;
  488. if (dst_rule.offset == 0)
  489. standard_offset = preferred_rule(standard_offset, dst_rule);
  490. else
  491. daylight_offset = preferred_rule(daylight_offset, dst_rule);
  492. }
  493. // In modern times, there will always be a standard rule in the TZDB, but that isn't true in
  494. // all time zones in or before the early 1900s. For example, the "US" rules begin in 1918.
  495. if (!standard_offset) {
  496. static DaylightSavingsOffset const empty_offset {};
  497. return { &empty_offset, &empty_offset };
  498. }
  499. return { standard_offset, daylight_offset ? daylight_offset : standard_offset };
  500. }
  501. static Offset get_active_dst_offset(TimeZoneOffset const& time_zone_offset, AK::Time time)
  502. {
  503. auto offsets = find_dst_offsets(time_zone_offset, time);
  504. if (offsets[0] == offsets[1])
  505. return { offsets[0]->offset, InDST::No };
  506. auto standard_time_in_effect = offsets[0]->time_in_effect(time);
  507. auto daylight_time_in_effect = offsets[1]->time_in_effect(time);
  508. if (daylight_time_in_effect < standard_time_in_effect) {
  509. if ((time < daylight_time_in_effect) || (time >= standard_time_in_effect))
  510. return { offsets[0]->offset, InDST::No };
  511. } else {
  512. if ((time >= standard_time_in_effect) && (time < daylight_time_in_effect))
  513. return { offsets[0]->offset, InDST::No };
  514. }
  515. return { offsets[1]->offset, InDST::Yes };
  516. }
  517. static TimeZoneOffset const& find_time_zone_offset(TimeZone time_zone, AK::Time time)
  518. {
  519. auto const& time_zone_offsets = s_time_zone_offsets[to_underlying(time_zone)];
  520. size_t index = 0;
  521. for (; index < time_zone_offsets.size(); ++index) {
  522. auto const& time_zone_offset = time_zone_offsets[index];
  523. if (!time_zone_offset.has_until || (time_zone_offset.until.time_since_epoch() > time))
  524. break;
  525. }
  526. VERIFY(index < time_zone_offsets.size());
  527. return time_zone_offsets[index];
  528. }
  529. Optional<Offset> get_time_zone_offset(TimeZone time_zone, AK::Time time)
  530. {
  531. auto const& time_zone_offset = find_time_zone_offset(time_zone, time);
  532. Offset dst_offset {};
  533. if (time_zone_offset.dst_rule != -1) {
  534. dst_offset = get_active_dst_offset(time_zone_offset, time);
  535. } else {
  536. auto in_dst = time_zone_offset.dst_offset == 0 ? InDST::No : InDST::Yes;
  537. dst_offset = { time_zone_offset.dst_offset, in_dst };
  538. }
  539. dst_offset.seconds += time_zone_offset.offset;
  540. return dst_offset;
  541. }
  542. Optional<Array<NamedOffset, 2>> get_named_time_zone_offsets(TimeZone time_zone, AK::Time time)
  543. {
  544. auto const& time_zone_offset = find_time_zone_offset(time_zone, time);
  545. Array<NamedOffset, 2> named_offsets;
  546. auto format_name = [](auto format, auto offset) -> String {
  547. if (offset == 0)
  548. return s_string_list[format].replace("{}"sv, ""sv, ReplaceMode::FirstOnly);
  549. return String::formatted(s_string_list[format], s_string_list[offset]);
  550. };
  551. auto set_named_offset = [&](auto& named_offset, auto dst_offset, auto in_dst, auto format, auto offset) {
  552. named_offset.seconds = time_zone_offset.offset + dst_offset;
  553. named_offset.in_dst = in_dst;
  554. named_offset.name = format_name(format, offset);
  555. };
  556. if (time_zone_offset.dst_rule != -1) {
  557. auto offsets = find_dst_offsets(time_zone_offset, time);
  558. auto in_dst = offsets[1]->offset == 0 ? InDST::No : InDST::Yes;
  559. set_named_offset(named_offsets[0], offsets[0]->offset, InDST::No, time_zone_offset.standard_format, offsets[0]->format);
  560. set_named_offset(named_offsets[1], offsets[1]->offset, in_dst, time_zone_offset.daylight_format, offsets[1]->format);
  561. } else {
  562. auto in_dst = time_zone_offset.dst_offset == 0 ? InDST::No : InDST::Yes;
  563. set_named_offset(named_offsets[0], time_zone_offset.dst_offset, in_dst, time_zone_offset.standard_format, 0);
  564. set_named_offset(named_offsets[1], time_zone_offset.dst_offset, in_dst, time_zone_offset.daylight_format, 0);
  565. }
  566. return named_offsets;
  567. }
  568. Optional<Location> get_time_zone_location(TimeZone time_zone)
  569. {
  570. auto is_valid_coordinate = [](auto const& coordinate) {
  571. return (coordinate.degrees != 0) || (coordinate.minutes != 0) || (coordinate.seconds != 0);
  572. };
  573. auto const& location = s_time_zone_locations[to_underlying(time_zone)];
  574. if (is_valid_coordinate(location.latitude) && is_valid_coordinate(location.longitude))
  575. return location;
  576. return {};
  577. }
  578. )~~~");
  579. generate_available_values(generator, "all_time_zones"sv, time_zone_data.time_zone_names);
  580. generator.append(R"~~~(
  581. }
  582. )~~~");
  583. TRY(file.write(generator.as_string_view().bytes()));
  584. return {};
  585. }
  586. ErrorOr<int> serenity_main(Main::Arguments arguments)
  587. {
  588. StringView generated_header_path;
  589. StringView generated_implementation_path;
  590. StringView time_zone_coordinates_path;
  591. Vector<StringView> time_zone_paths;
  592. Core::ArgsParser args_parser;
  593. args_parser.add_option(generated_header_path, "Path to the time zone data header file to generate", "generated-header-path", 'h', "generated-header-path");
  594. args_parser.add_option(generated_implementation_path, "Path to the time zone data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  595. 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");
  596. args_parser.add_positional_argument(time_zone_paths, "Paths to the time zone database files", "time-zone-paths");
  597. args_parser.parse(arguments);
  598. auto generated_header_file = TRY(open_file(generated_header_path, Core::Stream::OpenMode::Write));
  599. auto generated_implementation_file = TRY(open_file(generated_implementation_path, Core::Stream::OpenMode::Write));
  600. auto time_zone_coordinates_file = TRY(open_file(time_zone_coordinates_path, Core::Stream::OpenMode::Read));
  601. TimeZoneData time_zone_data {};
  602. for (auto time_zone_path : time_zone_paths)
  603. TRY(parse_time_zones(time_zone_path, time_zone_data));
  604. TRY(parse_time_zone_coordinates(*time_zone_coordinates_file, time_zone_data));
  605. TRY(generate_time_zone_data_header(*generated_header_file, time_zone_data));
  606. TRY(generate_time_zone_data_implementation(*generated_implementation_file, time_zone_data));
  607. return 0;
  608. }