Debian Codegraph @

time/date/virtual.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use sort;
5 use time;
6 use time::chrono;
7
8 // Flags for resolving undetermined zone-offsets. Handles timezone transitions.
9 //
10 // The [[realize]] function, as well as other date creation functions (e.g.
11 // [[new]], [[truncate]], [[reckon]]) accept zflags in place of a numerical
12 // zone-offset. If zflags are provided, these functions first calculate an
13 // intermediate date with a reasonable numerical zone-offset, usually some
14 // preexisting one or a best guess using some [[locality]].
15 //
16 // This intermediate date can be [[invalid]] if it falls within the observed gap
17 // or overlap of a timezone transition, where such dates are ambiguous or
18 // nonexistent. In this case, the provided zflags are consulted, and a final
19 // adjustment takes place before the final resultant date with a new zone-offset
20 // (or [[zfunresolved]]) is returned.
21 //
22 // Timezone transitions create gaps and overlaps, the two causes of [[invalid]]
23 // intermediate dates. Passing one "GAP_" and one "LAP_" flag covers both cases.
24 //
25 // let zf = date::zflag::LAP_EARLY | date::zflag::GAP_END;
26 // date::new(loc, zf, fields...)!; // will never return [[zfunresolved]]
27 //
28 // Note, "GAP_" flags will cause the resultant date to be different to the
29 // intermediate date if it falls within a gap.
30 //
31 // Flags with greater value take precedent.
32 //
33 // The following figures exist to help understand the effect of these flags.
34 //
35 // Fig A 2000 October 29th
36 // -1 hour
37 //
38 // f=02:30+0200
39 // g=02:30+0100
40 // lp | lq
41 // +0200 | | | +0100
42 // Observed time: 00 01 02 | 03 04 05
43 // Amsterdam: |-----|-----|==*==|-----|-----|
44 // . . .\ :: |. .
45 // . . . \: :| . .
46 // . . . : : . .
47 // . . . :\ |: . .
48 // . . . : \| : . .
49 // UTC: |-----|-----|--*--|--*--|-----|
50 // Contiguous time: 22 23 00 | 01 | 02 03
51 // | | |
52 // a tx b
53 //
54 // Fig A -- A backjump timezone transition in the Europe/Amsterdam locality.
55 // The transition is marked by "tx". There is an overlap in the chronology,
56 // marked by "lp" and "lq". The specified local time 02:30 falls within the
57 // observed overlap, and so has two valid zone-offsets and can be observed
58 // twice, as dates "f" and "g". When localized to UTC, these two observations
59 // correspond to UTC dates "a" and "b" respectively.
60 //
61 // Fig B 2000 March 26th
62 // +1 hour
63 //
64 // f~02:30+!!!!
65 // gp | gq
66 // +0100 | | | +0200
67 // Observed time: 00 01 02 | 03 04 05
68 // Amsterdam: |-----|-----| * |-----|-----|
69 // . . | / . .
70 // . . | / . .
71 // . . | / . .
72 // . . | / . .
73 // . . |/ . .
74 // UTC: |-----|-----|-----|-----|-----|
75 // Contiguous time: 23 00 01 02 03 04
76 // |
77 // tx
78 //
79 // Fig B -- A forejump timezone transition in the Europe/Amsterdam locality.
80 // The transition is marked by "tx". There is a gap in the chronology, marked by
81 // "gp" and "gq". The specified local time 02:30 falls within the observed gap,
82 // and so cannot be observed and is [[invalid]].
83 export type zflag = enum u8 {
84 // Assume a contiguous chronology with no observed gaps or overlaps.
85 // Upon encountering an observed gap or overlap, fail with [[invalid]].
86 // In other words, accept one and only one zone-offset.
87 CONTIG = 0b00000000,
88
89 // Upon encountering an observed overlap, select the earliest possible
90 // date (Fig A "f") using the most positive (eastmost) zone-offset.
91 LAP_EARLY = 0b00000001,
92 // Upon encountering an observed overlap, select the latest possible
93 // date (Fig A "g") using the most negative (westmost) zone-offset.
94 LAP_LATE = 0b00000010,
95
96 // Upon encountering an observed gap, disregard the intermediate date
97 // and select the date at the observed gap's start-boundary
98 // (Fig B "gp"), corresponding to the contiguous time just before the
99 // transition (Fig B "tx").
100 GAP_START = 0b00000100,
101 // Upon encountering an observed gap, disregard the intermediate date
102 // and select the date at the observed gap's end-boundary (Fig B "gq"),
103 // corresponding to the contiguous time at the transition (Fig B "tx").
104 GAP_END = 0b00001000,
105 };
106
107 // Failed to resolve an absent zone-offset. The provided [[zflag]]s failed to
108 // account for some timezone effect and could not produce a valid zone-offset.
109 export type zfunresolved = !zferror;
110
111 export type zferror = enum {
112 GAP,
113 LAP,
114 };
115
116 // A [[virtual]] date does not have enough information from which to create a
117 // valid [[date]].
118 export type insufficient = !void;
119
120 // A virtual date of undetermined validity; a [[date]] wrapper interface. It is
121 // meant as an intermediary container for date information to be resolved with
122 // the [[realize]] function.
123 //
124 // A virtual date's "observer" fields (including that of the embedded date)
125 // should be treated as writable. The [[realize]] function takes into account
126 // all these fields, except for the embedded [[time::chrono::moment]] and
127 // [[locality]] fields (.sec .nsec .tsc .loc).
128 //
129 // This can be used to safely construct a new [[date]] piece-by-piece. Start
130 // with [[newvirtual]], then collect enough date/time information incrementally
131 // by direct field assignments and/or with [[parse]]. Finish with [[realize]].
132 //
133 // let v = date::newvirtual();
134 // v.vloc = chrono::tz("Europe/Amsterdam")!;
135 // v.zoff = date::zflag::LAP_EARLY | date::zflag::GAP_END;
136 // date::parse(&v, "Date: %Y-%m-%d", "Date: 2000-01-02")!;
137 // v.hour = 15;
138 // v.minute = 4;
139 // v.second = 5;
140 // v.nanosecond = 600000000;
141 // let d = date::realize(v)!;
142 //
143 // Virtual date behaviour with the observer functions is undefined.
144 export type virtual = struct {
145 date,
146 // The virtual date's timescalar second.
147 vsec: (void | i64),
148 // The virtual date's nanosecond of the timescalar second.
149 vnsec: (void | i64),
150 // The virtual date's [[locality]].
151 vloc: (void | locality),
152 // The [[locality]]'s name.
153 locname: (void | str),
154 // The zone-offset. See [[zflag]] for its effects in [[realize]].
155 zoff: (void | time::duration | zflag),
156 // The zone-abbreviation.
157 zabbr: (void | str),
158 // The century; all but the last two digits of the year.
159 century: (void | int),
160 // The last two digits of the year; the year modulo 100.
161 year100: (void | int),
162 // The hour of a 12 hour clock; the hour modulo 12.
163 hour12: (void | int),
164 // The meridiem indicator (false=AM, true=PM).
165 ampm: (void | bool),
166 };
167
168 // Creates a new [[virtual]] date. All its fields are voided or nulled.
169 export fn newvirtual() virtual = virtual {
170 sec = 0,
171 nsec = 0,
172 tsc = &chrono::utc,
173 loc = UTC,
174 zonephase = null,
175 daydate = void,
176 daytime = void,
177
178 era = void,
179 year = void,
180 month = void,
181 day = void,
182 yearday = void,
183 isoweekyear = void,
184 isoweek = void,
185 week = void,
186 sundayweek = void,
187 weekday = void,
188
189 hour = void,
190 minute = void,
191 second = void,
192 nanosecond = void,
193
194 vsec = void,
195 vnsec = void,
196 vloc = void,
197 locname = void,
198 zoff = void,
199 zabbr = void,
200 century = void,
201 year100 = void,
202 hour12 = void,
203 ampm = void,
204 };
205
206 // Realizes a valid [[date]] from a [[virtual]] date, or fails appropriately.
207 //
208 // The virtual date must hold enough valid date information to calculate a
209 // resulting date. A valid combination of "inputs" (filled in, non-void fields)
210 // must be provided. For example:
211 //
212 // let v = date::newvirtual();
213 // v.locname = "Europe/Amsterdam";
214 // v.zoff = date::zflag::LAP_EARLY | date::zflag::GAP_END;
215 // date::parse(&v, // fills-in .year .month .day
216 // "Date: %Y-%m-%d", "Date: 2038-01-19")!;
217 // v.hour = 4;
218 // v.minute = 14;
219 // v.second = 7;
220 // v.nanosecond = 0;
221 // let d = date::realize(v, date::tzdb("Europe/Amsterdam")!)!;
222 //
223 // A fixed algorithm is used to ascertain the given input combination.
224 // Combinations are attempted in a particular order listed below.
225 // Inputs marked with '*' can be substituted with further combinations.
226 // The algorithm is as follows:
227 //
228 // The resultant date is made from a [[locality]] and [[time::instant]].
229 //
230 // The locality is derived from one of:
231 //
232 // - .vloc
233 // - .locname : This is compared to the .name field of each locality
234 // provided via the locs parameter, or "UTC" if none are provided.
235 // The first matching locality is used.
236 //
237 // The instant is derived from one of:
238 //
239 // - .vsec, .vnsec
240 // - .daydate*, .daytime*, .zoff : See [[zflag]] for its effects here.
241 //
242 // A void .daydate may be substituted with one of:
243 //
244 // - .year*, .month, .day
245 // - .year*, .yearday
246 // - .year*, .week, .weekday
247 // - .isoweekyear, .isoweek, .weekday
248 //
249 // A void .daytime may be substituted with:
250 //
251 // - .hour*, .minute, .second, .nanosecond
252 //
253 // A void .year may be substituted with:
254 //
255 // - .century, .year100
256 //
257 // A void .hour may be substituted with:
258 //
259 // - .hour12, .ampm
260 //
261 // If an insufficient combination was provided, [[insufficient]] is returned.
262 // If invalid values were provided, [[invalid]] is returned.
263 // Any [[zflag]]s assigned to the .zoff field affect the final result.
264 export fn realize(
265 v: virtual,
266 locs: locality...
267 ) (date | insufficient | invalid | zfunresolved | nomem) = {
268 // determine .loc
269 if (v.vloc is locality) {
270 v.loc = v.vloc as locality;
271 } else if (v.locname is str) {
272 for (let loc .. locs) {
273 if (loc.name == v.locname as str) {
274 v.loc = loc;
275 break;
276 };
277 };
278 } else {
279 return insufficient;
280 };
281
282 // try using .vsec .vnsec
283 if (v.vsec is i64 && v.vnsec is i64) {
284 return from_instant(
285 v.loc,
286 time::instant{
287 sec = v.vsec as i64,
288 nsec = v.vnsec as i64,
289 },
290 );
291 };
292
293 // try using .daydate, .daytime, .zoff
294 match (v.zoff) {
295 case void =>
296 return insufficient;
297 case time::duration =>
298 return realize_validzoff(v, locs...);
299 case let zf: zflag =>
300 let valid_dates = realize_validzoffs(v, locs...)?;
301 defer free(valid_dates);
302 switch (len(valid_dates)) {
303 case 0 =>
304 if (0 != zf & zflag::GAP_END) {
305 return realize_gapbounds(v).1;
306 } else if (0 != zf & zflag::GAP_START) {
307 return realize_gapbounds(v).0;
308 } else {
309 return zferror::GAP: zfunresolved;
310 };
311 case 1 =>
312 return valid_dates[0];
313 case =>
314 if (0 != zf & zflag::LAP_LATE) {
315 return valid_dates[len(valid_dates) - 1];
316 } else if (0 != zf & zflag::LAP_EARLY) {
317 return valid_dates[0];
318 } else {
319 return zferror::LAP: zfunresolved;
320 };
321 };
322 };
323 };
324
325 fn realize_validzoff(
326 v: virtual,
327 locs: locality...
328 ) (date | insufficient | invalid) = {
329 let d = realize_datetimezoff(v, locs...)?;
330
331 // verify zone offset
332 if (zone(&d).zoff != v.zoff as time::duration) {
333 return invalid;
334 };
335
336 return d;
337 };
338
339 // TODO: add .sundayweek to realize?
340
341 fn realize_datetimezoff(
342 v: virtual,
343 locs: locality...
344 ) (date | insufficient | invalid) = {
345 let lacking = false;
346
347 // determine zone offset
348 if (v.zoff is i64) {
349 void;
350 } else {
351 lacking = true;
352 };
353
354 // determine .daydate
355 if (v.daydate is i64) {
356 void;
357 } else :daydate {
358 const year =
359 if (v.year is int) {
360 yield v.year as int;
361 } else if (v.century is int && v.year100 is int) {
362 let cc = v.century as int;
363 let yy = v.year100 as int;
364 if (yy < 0 || yy > 99) {
365 return invalid;
366 };
367 yield cc * 100 + yy;
368 };
369
370 if (
371 v.month is int &&
372 v.day is int
373 ) {
374 v.daydate = calc_daydate__ymd(
375 year as int,
376 v.month as int,
377 v.day as int,
378 )?;
379 } else if (
380 v.yearday is int
381 ) {
382 v.daydate = calc_daydate__yd(
383 year as int,
384 v.yearday as int,
385 )?;
386 } else if (
387 v.week is int &&
388 v.weekday is int
389 ) {
390 v.daydate = calc_daydate__ywd(
391 year as int,
392 v.week as int,
393 v.weekday as int,
394 )?;
395 } else if (
396 v.isoweekyear is int &&
397 v.isoweek is int &&
398 v.weekday is int
399 ) {
400 v.daydate = calc_daydate__isoywd(
401 v.isoweekyear as int,
402 v.isoweek as int,
403 v.weekday as int,
404 )?;
405 } else {
406 // cannot deduce daydate
407 lacking = true;
408 };
409 };
410
411 // determine .daytime
412 if (v.daytime is i64) {
413 void;
414 } else :daytime {
415 const hour =
416 if (v.hour is int) {
417 yield v.hour as int;
418 } else if (v.hour12 is int && v.ampm is bool) {
419 const hr = v.hour12 as int;
420 const pm = v.ampm as bool;
421 yield if (pm) hr * 2 else hr;
422 } else {
423 lacking = true;
424 yield :daytime;
425 };
426
427 if (
428 v.minute is int &&
429 v.second is int &&
430 v.nanosecond is int
431 ) {
432 v.daytime = calc_daytime__hmsn(
433 hour,
434 v.minute as int,
435 v.second as int,
436 v.nanosecond as int,
437 )?;
438 } else {
439 lacking = true;
440 };
441 };
442
443 if (lacking) {
444 return insufficient;
445 };
446
447 // determine .sec, .nsec
448 const d = from_datetime(
449 v.loc,
450 v.zoff as time::duration,
451 v.daydate as i64,
452 v.daytime as i64,
453 );
454
455 return d;
456 };
457
458 fn realize_validzoffs(
459 v: virtual,
460 locs: locality...
461 ) ([]date | insufficient | invalid | nomem) = {
462 // check if only zoff is missing
463 v.zoff = 0o0;
464 match (realize_validzoff(v, locs...)) {
465 case (date | invalid) =>
466 void;
467 case let ins: insufficient =>
468 return ins;
469 };
470 v.zoff = void;
471
472 let ok = false;
473 let dates: []date = [];
474 defer if (!ok) free(dates);
475
476 // try matching zone abbreviation
477 if (v.zabbr is str) {
478 for (let zone .. v.loc.phases) {
479 if (v.zabbr as str == zone.abbr) {
480 v.zoff = zone.zoff;
481 match (realize_validzoff(v, locs...)) {
482 case let d: date =>
483 match (sort::search(
484 dates, size(date), &d, &cmpdates,
485 )) {
486 case size =>
487 void;
488 case void =>
489 append(dates, d)?;
490 sort::sort(dates, size(date), &cmpdates)?;
491 };
492 case invalid =>
493 continue;
494 case =>
495 abort();
496 };
497 };
498 };
499
500 return invalid;
501 };
502
503 // try zone offsets from locality
504 for (let zone .. v.loc.phases) {
505 v.zoff = zone.zoff;
506 match (realize_validzoff(v, locs...)) {
507 case let d: date =>
508 match (sort::search(dates, size(date), &d, &cmpdates)) {
509 case size =>
510 void;
511 case void =>
512 append(dates, d)?;
513 sort::sort(dates, size(date), &cmpdates)?;
514 };
515 case invalid =>
516 continue;
517 case =>
518 abort();
519 };
520 };
521
522 ok = true;
523 return dates;
524 };
525
526 fn cmpdates(a: const *opaque, b: const *opaque) int = {
527 let a = a: *date;
528 let b = b: *date;
529 return chrono::compare(a, b)!: int;
530 };
531
532 fn realize_gapbounds(v: virtual) (date, date) = {
533 let loc = v.loc;
534
535 let zlo: time::duration = 2 * loc.daylength;
536 let zhi: time::duration = 2 * -loc.daylength;
537 for (let zone .. loc.phases) {
538 if (zone.zoff > zhi) {
539 zhi = zone.zoff;
540 };
541 if (zone.zoff < zlo) {
542 zlo = zone.zoff;
543 };
544 };
545
546 v.zoff = zhi;
547 let earliest = realize_datetimezoff(v)!;
548 let earliest = *(&earliest: *time::instant);
549
550 v.zoff = zlo;
551 let latest = realize_datetimezoff(v)!;
552 let latest = *(&latest: *time::instant);
553
554 let t = time::instant{ ... };
555 for (let tr .. loc.transitions) {
556 let is_within_bounds = (
557 time::compare(earliest, tr.when) < 0
558 && time::compare(latest, tr.when) > 0
559 );
560
561 if (is_within_bounds) {
562 t = tr.when;
563 break;
564 };
565 };
566
567 let gapstart = from_instant(loc, time::add(t, -time::NANOSECOND));
568 let gapend = from_instant(loc, t);
569
570 return (gapstart, gapend);
571 };