GenerateTimeZoneData.cpp 27 KB

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