Debian Codegraph @

tools/tclZIC.tcl

raw
1 #----------------------------------------------------------------------
2 #
3 # tclZIC.tcl --
4 #
5 # Take the time zone data source files from Arthur Olson's
6 # repository at https://www.iana.org/time-zones, and prepare time zone
7 # information files for Tcl.
8 #
9 # Usage:
10 # tclsh tclZIC.tcl inputDir outputDir
11 #
12 # Parameters:
13 # inputDir - Directory (e.g., tzdata2022a) where Olson's source
14 # files are to be found.
15 # outputDir - Directory (e.g., ../library/tzdata) where
16 # the time zone information files are to be placed.
17 #
18 # Results:
19 # May produce error messages on the standard error. An exit
20 # code of zero denotes success; any other exit code is failure.
21 #
22 # This program parses the timezone data in a means analogous to the
23 # 'zic' command, and produces Tcl time zone information files suitable
24 # for loading into the 'clock' namespace.
25 #
26 #----------------------------------------------------------------------
27 #
28 # Copyright (c) 2004 Kevin B. Kenny. All rights reserved.
29 # See the file "license.terms" for information on usage and redistribution
30 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
31 #----------------------------------------------------------------------
32
33 # Define the names of the Olson files that we need to load.
34 # We avoid the solar time files and the leap seconds.
35
36 set olsonFiles {
37 africa antarctica asia australasia
38 backward etcetera europe northamerica
39 southamerica
40 }
41
42 # Define the year at which the DST information will stop.
43
44 set maxyear 2100
45
46 # Determine how big a wide integer is.
47
48 set MAXWIDE [expr {wide(1)}]
49 while 1 {
50 set next [expr {wide($MAXWIDE + $MAXWIDE + 1)}]
51 if {$next < 0} {
52 break
53 }
54 set MAXWIDE $next
55 }
56 set MINWIDE [expr {-$MAXWIDE-1}]
57
58 #----------------------------------------------------------------------
59 #
60 # loadFiles --
61 #
62 # Loads the time zone files for each continent into memory
63 #
64 # Parameters:
65 # dir - Directory where the time zone source files are found
66 #
67 # Results:
68 # None.
69 #
70 # Side effects:
71 # Calls 'loadZIC' for each continent's data file in turn.
72 # Reports progress on stdout.
73 #
74 #----------------------------------------------------------------------
75
76 proc loadFiles {dir} {
77 variable olsonFiles
78 foreach file $olsonFiles {
79 puts "loading: [file join $dir $file]"
80 loadZIC [file join $dir $file]
81 }
82 return
83 }
84
85 #----------------------------------------------------------------------
86 #
87 # checkForwardRuleRefs --
88 #
89 # Checks to make sure that all references to Daylight Saving
90 # Time rules designate defined rules.
91 #
92 # Parameters:
93 # None.
94 #
95 # Results:
96 # None.
97 #
98 # Side effects:
99 # Produces an error message and increases the error count if
100 # any undefined rules are present.
101 #
102 #----------------------------------------------------------------------
103
104 proc checkForwardRuleRefs {} {
105 variable forwardRuleRefs
106 variable rules
107
108 foreach {rule where} [array get forwardRuleRefs] {
109 if {![info exists rules($rule)]} {
110 foreach {fileName lno} $where {
111 puts stderr "$fileName:$lno:can't locate rule \"$rule\""
112 incr errorCount
113 }
114 }
115 }
116 }
117
118 #----------------------------------------------------------------------
119 #
120 # loadZIC --
121 #
122 # Load one continent's data into memory.
123 #
124 # Parameters:
125 # fileName -- Name of the time zone source file.
126 #
127 # Results:
128 # None.
129 #
130 # Side effects:
131 # The global variable, 'errorCount' counts the number of errors.
132 # The global array, 'links', contains a distillation of the
133 # 'Link' directives in the file. The keys are 'links to' and
134 # the values are 'links from'. The 'parseRule' and 'parseZone'
135 # procedures are called to handle 'Rule' and 'Zone' directives.
136 #
137 #----------------------------------------------------------------------
138
139 proc loadZIC {fileName} {
140 variable errorCount
141 variable links
142
143 # Suck the text into memory.
144
145 set f [open $fileName r]
146 set data [read $f]
147 close $f
148
149 # Break the input into lines, and count line numbers.
150
151 set lno 0
152 foreach line [split $data \n] {
153 incr lno
154
155 # Break a line of input into words.
156
157 regsub {\s*(\#.*)?$} $line {} line
158 if {$line eq ""} {
159 continue
160 }
161 set words {}
162 if {[regexp {^\s} $line]} {
163 # Detect continuations of a zone and flag the list appropriately
164 lappend words ""
165 }
166 lappend words {*}[regexp -all -inline {\S+} $line]
167
168 # Switch on the directive
169
170 switch -exact -- [lindex $words 0] {
171 Rule {
172 parseRule $fileName $lno $words
173 }
174 Link {
175 set links([lindex $words 2]) [lindex $words 1]
176 }
177 Zone {
178 set lastZone [lindex $words 1]
179 set until [parseZone $fileName $lno \
180 $lastZone [lrange $words 2 end] "minimum"]
181 }
182 {} {
183 set i 0
184 foreach word $words {
185 if {[lindex $words $i] ne ""} {
186 break
187 }
188 incr i
189 }
190 set words [lrange $words $i end]
191 set until [parseZone $fileName $lno $lastZone $words $until]
192 }
193 default {
194 incr errorCount
195 puts stderr "$fileName:$lno:unknown line type \"[lindex $words 0]\""
196 }
197 }
198 }
199
200 return
201 }
202
203 #----------------------------------------------------------------------
204 #
205 # parseRule --
206 #
207 # Parses a Rule directive in an Olson file.
208 #
209 # Parameters:
210 # fileName -- Name of the file being parsed.
211 # lno - Line number within the file
212 # words - The line itself, broken into words.
213 #
214 # Results:
215 # None.
216 #
217 # Side effects:
218 # The rule is analyzed and added to the 'rules' array.
219 # Errors are reported and counted.
220 #
221 #----------------------------------------------------------------------
222
223 proc parseRule {fileName lno words} {
224 variable rules
225 variable errorCount
226
227 # Break out the columns
228
229 lassign $words Rule name from to type in on at save letter
230
231 # Handle the 'only' keyword
232
233 if {$to eq "only"} {
234 set to $from
235 }
236
237 # Process the start year
238
239 if {![string is integer $from]} {
240 if {![string equal -length [string length $from] $from "minimum"]} {
241 puts stderr "$fileName:$lno:FROM field \"$from\" not an integer."
242 incr errorCount
243 return
244 } else {
245 set from "minimum"
246 }
247 }
248
249 # Process the end year
250
251 if {![string is integer $to]} {
252 if {![string equal -length [string length $to] $to "maximum"]} {
253 puts stderr "$fileName:$lno:TO field \"$to\" not an integer."
254 incr errorCount
255 return
256 } else {
257 set to "maximum"
258 }
259 }
260
261 # Process the type of year in which the rule applies
262
263 if {$type ne "-"} {
264 puts stderr "$fileName:$lno:year types are not yet supported."
265 incr errorCount
266 return
267 }
268
269 # Process the month in which the rule starts
270
271 if {[catch {lookupMonth $in} in]} {
272 puts stderr "$fileName:$lno:$in"
273 incr errorCount
274 return
275 }
276
277 # Process the day of the month on which the rule starts
278
279 if {[catch {parseON $on} on]} {
280 puts stderr "$fileName:$lno:$on"
281 incr errorCount
282 return
283 }
284
285 # Process the time of day on which the rule starts
286
287 if {[catch {parseTOD $at} at]} {
288 puts stderr "$fileName:$lno:$at"
289 incr errorCount
290 return
291 }
292
293 # Process the DST adder
294
295 if {[catch {parseOffsetTime $save} save]} {
296 puts stderr "$fileName:$lno:$save"
297 incr errorCount
298 return
299 }
300
301 # Process the letter to use for summer time
302
303 if {$letter eq "-"} {
304 set letter ""
305 }
306
307 # Accumulate all the data.
308
309 lappend rules($name) $from $to $type $in $on $at $save $letter
310 return
311
312 }
313
314 #----------------------------------------------------------------------
315 #
316 # parseON --
317 #
318 # Parse a specification for a day of the month
319 #
320 # Parameters:
321 # on - the ON field from a line in an Olson file.
322 #
323 # Results:
324 # Returns a partial Tcl command. When the year and number of the
325 # month are appended, the command will return the Julian Day Number
326 # of the desired date.
327 #
328 # Side effects:
329 # None.
330 #
331 # The specification can be:
332 # - a simple number, which designates a constant date.
333 # - The name of a weekday, followed by >= or <=, followed by a number.
334 # This designates the nearest occurrence of the given weekday on
335 # or before (on or after) the given day of the month.
336 # - The word 'last' followed by a weekday name with no intervening
337 # space. This designates the last occurrence of the given weekday
338 # in the month.
339 #
340 #----------------------------------------------------------------------
341
342 proc parseON {on} {
343 if {![regexp -expanded {
344 ^(?:
345 # first possibility - simple number - field 1
346 ([[:digit:]]+)
347 |
348 # second possibility - weekday >= (or <=) number
349 # field 2 - weekday
350 ([[:alpha:]]+)
351 # field 3 - direction
352 ([<>]=)
353 # field 4 - number
354 ([[:digit:]]+)
355 |
356 # third possibility - lastWeekday - field 5
357 last([[:alpha:]]+)
358 )$
359 } $on -> dom1 wday2 dir2 num2 wday3]} {
360 error "can't parse ON field \"$on\""
361 }
362 if {$dom1 ne ""} {
363 return [list onDayOfMonth $dom1]
364 } elseif {$wday2 ne ""} {
365 set wday2 [lookupDayOfWeek $wday2]
366 return [list onWeekdayInMonth $wday2 $dir2 $num2]
367 } elseif {$wday3 ne ""} {
368 set wday3 [lookupDayOfWeek $wday3]
369 return [list onLastWeekdayInMonth $wday3]
370 } else {
371 error "in parseOn \"$on\": can't happen"
372 }
373 }
374
375 #----------------------------------------------------------------------
376 #
377 # onDayOfMonth --
378 #
379 # Find a given day of a given month
380 #
381 # Parameters:
382 # day - Day of the month
383 # year - Gregorian year
384 # month - Number of the month (1-12)
385 #
386 # Results:
387 # Returns the Julian Day Number of the desired day.
388 #
389 # Side effects:
390 # None.
391 #
392 #----------------------------------------------------------------------
393
394 proc onDayOfMonth {day year month} {
395 scan $day %d day
396 scan $year %d year
397 scan $month %d month
398 set date [::tcl::clock::GetJulianDayFromEraYearMonthDay \
399 [dict create era CE year $year month $month dayOfMonth $day] \
400 2361222]
401 return [dict get $date julianDay]
402 }
403
404 #----------------------------------------------------------------------
405 #
406 # onWeekdayInMonth --
407 #
408 # Find the weekday falling on or after (on or before) a
409 # given day of the month
410 #
411 # Parameters:
412 # dayOfWeek - Day of the week (Monday=1, Sunday=7)
413 # relation - <= for the weekday on or before a given date, >= for
414 # the weekday on or after the given date.
415 # dayOfMonth - Day of the month
416 # year - Gregorian year
417 # month - Number of the month (1-12)
418 #
419 # Results:
420 # Returns the Juloan Day Number of the desired day.
421 #
422 # Side effects:
423 # None.
424 #
425 # onWeekdayInMonth is used to compute Daylight Saving Time rules
426 # like 'Sun>=1' (for the nearest Sunday on or after the first of the month)
427 # or "Mon<=4' (for the Monday on or before the fourth of the month).
428 #
429 #----------------------------------------------------------------------
430
431 proc onWeekdayInMonth {dayOfWeek relation dayOfMonth year month} {
432 set date [::tcl::clock::GetJulianDayFromEraYearMonthDay [dict create \
433 era CE year $year month $month dayOfMonth $dayOfMonth] 2361222]
434 switch -exact -- $relation {
435 <= {
436 return [::tcl::clock::WeekdayOnOrBefore $dayOfWeek \
437 [dict get $date julianDay]]
438 }
439 >= {
440 return [::tcl::clock::WeekdayOnOrBefore $dayOfWeek \
441 [expr {[dict get $date julianDay] + 6}]]
442 }
443 }
444 }
445
446 #----------------------------------------------------------------------
447 #
448 # onLastWeekdayInMonth --
449 #
450 # Find the last instance of a given weekday in a month.
451 #
452 # Parameters:
453 # dayOfWeek - Weekday to find (Monday=1, Sunday=7)
454 # year - Gregorian year
455 # month - Month (1-12)
456 #
457 # Results:
458 # Returns the Julian Day number of the last instance of
459 # the given weekday in the given month
460 #
461 # Side effects:
462 # None.
463 #
464 #----------------------------------------------------------------------
465
466 proc onLastWeekdayInMonth {dayOfWeek year month} {
467 incr month
468 # Find day 0 of the following month, which is the last day of
469 # the current month. Yes, it works to ask for day 0 of month 13!
470 set date [::tcl::clock::GetJulianDayFromEraYearMonthDay [dict create \
471 era CE year $year month $month dayOfMonth 0] 2361222]
472 return [::tcl::clock::WeekdayOnOrBefore $dayOfWeek \
473 [dict get $date julianDay]]
474 }
475
476 #----------------------------------------------------------------------
477 #
478 # parseTOD --
479 #
480 # Parses the specification of a time of day in an Olson file.
481 #
482 # Parameters:
483 # tod - Time of day, which may be followed by 'w', 's', 'u', 'g'
484 # or 'z'. 'w' (or no letter) designates a wall clock time,
485 # 's' designates Standard Time in the given zone, and
486 # 'u', 'g', and 'z' all designate UTC.
487 #
488 # Results:
489 # Returns a two element list containing a count of seconds from
490 # midnight and the letter that followed the time.
491 #
492 # Side effects:
493 # Reports and counts an error if the time cannot be parsed.
494 #
495 #----------------------------------------------------------------------
496
497 proc parseTOD {tod} {
498 if {![regexp -expanded {
499 ^
500 ([[:digit:]]{1,2}) # field 1 - hour
501 (?:
502 :([[:digit:]]{2}) # field 2 - minute
503 (?:
504 :([[:digit:]]{2}) # field 3 - second
505 )?
506 )?
507 (?:
508 ([wsugz]) # field 4 - type indicator
509 )?
510 } $tod -> hour minute second ind]} {
511 puts stderr "$fileName:$lno:can't parse time field \"$tod\""
512 incr errorCount
513 }
514 scan $hour %d hour
515 if {$minute ne ""} {
516 scan $minute %d minute
517 } else {
518 set minute 0
519 }
520 if {$second ne ""} {
521 scan $second %d second
522 } else {
523 set second 0
524 }
525 if {$ind eq ""} {
526 set ind w
527 }
528 return [list [expr {($hour * 60 + $minute) * 60 + $second}] $ind]
529 }
530
531 #----------------------------------------------------------------------
532 #
533 # parseOffsetTime --
534 #
535 # Parses the specification of an offset time in an Olson file.
536 #
537 # Parameters:
538 # offset - Offset time as [+-]hh:mm:ss
539 #
540 # Results:
541 # Returns the offset time as a count of seconds.
542 #
543 # Side effects:
544 # Reports and counts an error if the time cannot be parsed.
545 #
546 #----------------------------------------------------------------------
547
548 proc parseOffsetTime {offset} {
549 if {![regexp -expanded {
550 ^
551 ([-+])? # field 1 - signum
552 ([[:digit:]]{1,2}) # field 2 - hour
553 (?:
554 :([[:digit:]]{2}) # field 3 - minute
555 (?:
556 :([[:digit:]]{2}) # field 4 - second
557 )?
558 )?
559 } $offset -> signum hour minute second]} {
560 puts stderr "$fileName:$lno:can't parse offset time \"$offset\""
561 incr errorCount
562 }
563 append signum 1
564 scan $hour %d hour
565 if {$minute ne ""} {
566 scan $minute %d minute
567 } else {
568 set minute 0
569 }
570 if {$second ne ""} {
571 scan $second %d second
572 } else {
573 set second 0
574 }
575 return [expr {(($hour * 60 + $minute) * 60 + $second) * $signum}]
576
577 }
578
579 #----------------------------------------------------------------------
580 #
581 # lookupMonth -
582 # Looks up a month by name
583 #
584 # Parameters:
585 # month - Name of a month.
586 #
587 # Results:
588 # Returns the number of the month.
589 #
590 # Side effects:
591 # None.
592 #
593 #----------------------------------------------------------------------
594
595 proc lookupMonth {month} {
596 set indx [lsearch -regexp {
597 {} January February March April May June
598 July August September October November December
599 } ${month}.*]
600 if {$indx < 1} {
601 error "unknown month name \"$month\""
602 }
603 return $indx
604 }
605
606 #----------------------------------------------------------------------
607 #
608 # lookupDayOfWeek --
609 #
610 # Looks up the name of a weekday.
611 #
612 # Parameters:
613 # wday - Weekday name (or a unique prefix).
614 #
615 # Results:
616 # Returns the weekday number (Monday=1, Sunday=7)
617 #
618 # Side effects:
619 # None.
620 #
621 #----------------------------------------------------------------------
622
623 proc lookupDayOfWeek {wday} {
624 set indx [lsearch -regexp {
625 {} Monday Tuesday Wednesday Thursday Friday Saturday Sunday
626 } ${wday}.*]
627 if {$indx < 1} {
628 error "unknown weekday name \"$wday\""
629 }
630 return $indx
631 }
632
633 #----------------------------------------------------------------------
634 #
635 # parseZone --
636 #
637 # Parses a Zone directive in an Olson file
638 #
639 # Parameters:
640 # fileName -- Name of the file being parsed.
641 # lno -- Line number within the file.
642 # zone -- Name of the time zone
643 # words -- Remaining words on the line.
644 # start -- 'Until' time from the previous line if this is a
645 # continuation line, or 'minimum' if this is the first line.
646 #
647 # Results:
648 # Returns the 'until' field of the current line
649 #
650 # Side effects:
651 # Stores a row in the 'zones' array describing the current zone.
652 # The row consists of a start time (year month day tod), a Standard
653 # Time offset from Greenwich, a Daylight Saving Time offset from
654 # Standard Time, and a format for printing the time zone.
655 #
656 # The start time is the result of an earlier call to 'parseUntil'
657 # or else the keyword 'minimum'. The GMT offset is the
658 # result of a call to 'parseOffsetTime'. The Daylight Saving
659 # Time offset is represented as a partial Tcl command. To the
660 # command will be appended a start time (seconds from epoch)
661 # the current offset of Standard Time from Greenwich, the current
662 # offset of Daylight Saving Time from Greenwich, the default
663 # offset from this line, the name pattern from this line,
664 # the 'until' field from this line, and a variable name where points
665 # are to be stored. This command is implemented by the 'applyNoRule',
666 # 'applyDSTOffset' and 'applyRules' procedures.
667 #
668 #----------------------------------------------------------------------
669
670 proc parseZone {fileName lno zone words start} {
671 variable zones
672 variable rules
673 variable errorCount
674 variable forwardRuleRefs
675
676 lassign $words gmtoff save format
677 if {[catch {parseOffsetTime $gmtoff} gmtoff]} {
678 puts stderr "$fileName:$lno:$gmtoff"
679 incr errorCount
680 return
681 }
682 if {[info exists rules($save)]} {
683 set save [list applyRules $save]
684 } elseif {$save eq "-"} {
685 set save [list applyNoRule]
686 } elseif {[catch {parseOffsetTime $save} save2]} {
687 lappend forwardRuleRefs($save) $fileName $lno
688 set save [list applyRules $save]
689 } else {
690 set save [list applyDSTOffset $save2]
691 }
692 lappend zones($zone) $start $gmtoff $save $format
693 if {[llength $words] >= 4} {
694 return [parseUntil [lrange $words 3 end]]
695 } else {
696 return {}
697 }
698 }
699
700 #----------------------------------------------------------------------
701 #
702 # parseUntil --
703 #
704 # Parses the 'UNTIL' part of a 'Zone' directive.
705 #
706 # Parameters:
707 # words - The 'UNTIL' part of the directie.
708 #
709 # Results:
710 # Returns a list comprising the year, the month, the day, and
711 # the time of day. Time of day is represented as the result of
712 # 'parseTOD'.
713 #
714 #----------------------------------------------------------------------
715
716 proc parseUntil {words} {
717 variable firstYear
718
719 if {[llength $words] >= 1} {
720 set year [lindex $words 0]
721 if {![string is integer $year]} {
722 error "can't parse UNTIL field \"$words\""
723 }
724 if {![info exists firstYear] || $year < $firstYear} {
725 set firstYear $year
726 }
727 } else {
728 set year "maximum"
729 }
730 if {[llength $words] >= 2} {
731 set month [lookupMonth [lindex $words 1]]
732 } else {
733 set month 1
734 }
735 if {[llength $words] >= 3} {
736 set day [parseON [lindex $words 2]]
737 } else {
738 set day {onDayOfMonth 1}
739 }
740 if {[llength $words] >= 4} {
741 set tod [parseTOD [lindex $words 3]]
742 } else {
743 set tod {0 w}
744 }
745 return [list $year $month $day $tod]
746 }
747
748 #----------------------------------------------------------------------
749 #
750 # applyNoRule --
751 #
752 # Generates time zone data for a zone without Daylight Saving
753 # Time.
754 #
755 # Parameters:
756 # year - Year in which the rule applies
757 # startSecs - Time at which the rule starts.
758 # stdGMTOffset - Offset from Greenwich prior to the start of the
759 # rule
760 # DSTOffset - Offset of Daylight from Standard prior to the
761 # start of the rule.
762 # nextGMTOffset - Offset from Greenwich when the rule is in effect.
763 # namePattern - Name of the timezone.
764 # until - Time at which the rule expires.
765 # pointsVar - Name of a variable in callers scope that receives
766 # transition times
767 #
768 # Results:
769 # Returns a two element list comprising 'nextGMTOffset' and
770 # 0 - the zero indicates that Daylight Saving Time is not
771 # in effect.
772 #
773 # Side effects:
774 # Appends a row to the 'points' variable comprising the start time,
775 # the offset from GMT, a zero (indicating that DST is not in effect),
776 # and the name of the time zone.
777 #
778 #----------------------------------------------------------------------
779
780 proc applyNoRule {year startSecs stdGMTOffset DSTOffset nextGMTOffset
781 namePattern until pointsVar} {
782 upvar 1 $pointsVar points
783 lappend points $startSecs $nextGMTOffset 0 \
784 [convertNamePattern $namePattern -]
785 return [list $nextGMTOffset 0]
786 }
787
788 #----------------------------------------------------------------------
789 #
790 # applyDSTOffset --
791 #
792 # Generates time zone data for a zone with permanent Daylight
793 # Saving Time.
794 #
795 # Parameters:
796 # nextDSTOffset - Offset of Daylight from Standard while the
797 # rule is in effect.
798 # year - Year in which the rule applies
799 # startSecs - Time at which the rule starts.
800 # stdGMTOffset - Offset from Greenwich prior to the start of the
801 # rule
802 # DSTOffset - Offset of Daylight from Standard prior to the
803 # start of the rule.
804 # nextGMTOffset - Offset from Greenwich when the rule is in effect.
805 # namePattern - Name of the timezone.
806 # until - Time at which the rule expires.
807 # pointsVar - Name of a variable in callers scope that receives
808 # transition times
809 #
810 # Results:
811 # Returns a two element list comprising 'nextGMTOffset' and
812 # 'nextDSTOffset'.
813 #
814 # Side effects:
815 # Appends a row to the 'points' variable comprising the start time,
816 # the offset from GMT, a one (indicating that DST is in effect),
817 # and the name of the time zone.
818 #
819 #----------------------------------------------------------------------
820
821 proc applyDSTOffset {nextDSTOffset year startSecs
822 stdGMTOffset DSTOffset nextGMTOffset
823 namePattern until pointsVar} {
824 upvar 1 $pointsVar points
825 lappend points \
826 $startSecs \
827 [expr {$nextGMTOffset + $nextDSTOffset}] \
828 1 \
829 [convertNamePattern $namePattern S]
830 return [list $nextGMTOffset $nextDSTOffset]
831 }
832
833 #----------------------------------------------------------------------
834 #
835 # applyRules --
836 #
837 # Applies a rule set to a time zone for a given range of time
838 #
839 # Parameters:
840 # ruleSet - Name of the rule set to apply
841 # year - Starting year for the rules
842 # startSecs - Time at which the rules begin to apply
843 # stdGMTOffset - Offset from Greenwich prior to the start of the
844 # rules.
845 # DSTOffset - Offset of Daylight from Standard prior to the
846 # start of the rules.
847 # nextGMTOffset - Offset from Greenwich when the rules are in effect.
848 # namePattern - Name pattern for the time zone.
849 # until - Time at which the rule set expires.
850 # pointsVar - Name of a variable in callers scope that receives
851 # transition times
852 #
853 # Results:
854 # Returns a two element list comprising the offset from GMT
855 # to Standard and the offset from Standard to Daylight (if DST
856 # is in effect) at the end of the period in which the rules apply
857 #
858 # Side effects:
859 # Appends one or more rows to the 'points' variable, each of which
860 # comprises a transition time, the offset from GMT that is
861 # in effect after the transition, a flag for whether DST is in
862 # effect, and the name of the time zone.
863 #
864 #----------------------------------------------------------------------
865
866 proc applyRules {ruleSet year startSecs stdGMTOffset DSTOffset nextGMTOffset
867 namePattern until pointsVar} {
868 variable done
869 variable rules
870 variable maxyear
871
872 upvar 1 $pointsVar points
873
874 # Extract the rules that apply to the current year, and the number
875 # of rules (now or in future) that will end at a specific year.
876 # Ignore rules entirely in the past.
877
878 lassign [divideRules $ruleSet $year] currentRules nSunsetRules
879
880 # If the first transition is later than $startSecs, and $stdGMTOffset is
881 # different from $nextGMTOffset, we will need an initial record like:
882 # lappend points $startSecs $stdGMTOffset 0 \
883 # [convertNamePattern $namePattern -]
884
885 set didTransitionIn false
886
887 # Determine the letter to use in Standard Time
888
889 set prevLetter ""
890 foreach {
891 fromYear toYear yearType monthIn daySpecOn timeAt save letter
892 } $rules($ruleSet) {
893 if {$save == 0} {
894 set prevLetter $letter
895 break
896 }
897 }
898
899 # Walk through each year in turn. This loop will break when
900 # (a) the 'until' time is passed
901 # or (b) the 'until' time is empty and all remaining rules extend to
902 # the end of time
903
904 set stdGMTOffset $nextGMTOffset
905
906 # convert "until" to seconds from epoch in current time zone
907
908 if {$until ne ""} {
909 lassign $until untilYear untilMonth untilDaySpec untilTimeOfDay
910 lappend untilDaySpec $untilYear $untilMonth
911 set untilJCD [eval $untilDaySpec]
912 set untilBaseSecs [expr {
913 wide(86400) * wide($untilJCD) - 210866803200 }]
914 set untilSecs [convertTimeOfDay $untilBaseSecs $stdGMTOffset \
915 $DSTOffset {*}$untilTimeOfDay]
916 }
917
918 set origStartSecs $startSecs
919
920 while {($until ne "" && $startSecs < $untilSecs)
921 || ($until eq "" && ($nSunsetRules > 0 || $year < $maxyear))} {
922 set remainingRules $currentRules
923 while {[llength $remainingRules] > 0} {
924
925 # Find the rule with the earliest start time from among the
926 # active rules that haven't yet been processed.
927
928 lassign [findEarliestRule $remainingRules $year \
929 $stdGMTOffset $DSTOffset] earliestSecs earliestIndex
930
931 set endi [expr {$earliestIndex + 7}]
932 set rule [lrange $remainingRules $earliestIndex $endi]
933 lassign $rule fromYear toYear \
934 yearType monthIn daySpecOn timeAt save letter
935
936 # Test if the rule is in effect.
937
938 if {
939 $earliestSecs > $startSecs &&
940 ($until eq "" || $earliestSecs < $untilSecs)
941 } {
942 # Test if the initial transition has been done.
943 # If not, do it now.
944
945 if {!$didTransitionIn && $earliestSecs > $origStartSecs} {
946 set nm [convertNamePattern $namePattern $prevLetter]
947 lappend points \
948 $origStartSecs \
949 [expr {$stdGMTOffset + $DSTOffset}] \
950 0 \
951 $nm
952 set didTransitionIn true
953 }
954
955 # Add a row to 'points' for the rule
956
957 set nm [convertNamePattern $namePattern $letter]
958 lappend points \
959 $earliestSecs \
960 [expr {$stdGMTOffset + $save}] \
961 [expr {$save != 0}] \
962 $nm
963 }
964
965 # Remove the rule just applied from the queue
966
967 set remainingRules [lreplace \
968 $remainingRules[set remainingRules {}] \
969 $earliestIndex $endi]
970
971 # Update current DST offset and time zone letter
972
973 set DSTOffset $save
974 set prevLetter $letter
975
976 # Reconvert the 'until' time in the current zone.
977
978 if {$until ne ""} {
979 set untilSecs [convertTimeOfDay $untilBaseSecs \
980 $stdGMTOffset $DSTOffset {*}$untilTimeOfDay]
981 }
982 }
983
984 # Advance to the next year
985
986 incr year
987 set date [::tcl::clock::GetJulianDayFromEraYearMonthDay \
988 [dict create era CE year $year month 1 dayOfMonth 1] 2361222]
989 set startSecs [expr {
990 [dict get $date julianDay] * wide(86400) - 210866803200
991 - $stdGMTOffset - $DSTOffset
992 }]
993
994 # Get rules in effect in the new year.
995
996 lassign [divideRules $ruleSet $year] currentRules nSunsetRules
997 }
998
999 return [list $stdGMTOffset $DSTOffset]
1000 }
1001
1002 #----------------------------------------------------------------------
1003 #
1004 # divideRules --
1005 # Determine what Daylight Saving Time rules may be in effect in
1006 # a given year.
1007 #
1008 # Parameters:
1009 # ruleSet - Set of rules from 'parseRule'
1010 # year - Year to test
1011 #
1012 # Results:
1013 # Returns a two element list comprising the subset of 'ruleSet'
1014 # that is in effect in the given year, and the count of rules
1015 # that expire in the future (as opposed to those that expire in
1016 # the past or not at all). If this count is zero, the rules do
1017 # not change in future years.
1018 #
1019 # Side effects:
1020 # None.
1021 #
1022 #----------------------------------------------------------------------
1023
1024 proc divideRules {ruleSet year} {
1025 variable rules
1026
1027 set currentRules {}
1028 set nSunsetRules 0
1029
1030 foreach {
1031 fromYear toYear yearType monthIn daySpecOn timeAt save letter
1032 } $rules($ruleSet) {
1033 if {$toYear ne "maximum" && $year > $toYear} {
1034 # ignore - rule is in the past
1035 } else {
1036 if {$fromYear eq "minimum" || $fromYear <= $year} {
1037 lappend currentRules $fromYear $toYear $yearType $monthIn \
1038 $daySpecOn $timeAt $save $letter
1039 }
1040 if {$toYear ne "maximum"} {
1041 incr nSunsetRules
1042 }
1043 }
1044 }
1045
1046 return [list $currentRules $nSunsetRules]
1047
1048 }
1049
1050 #----------------------------------------------------------------------
1051 #
1052 # findEarliestRule --
1053 #
1054 # Find the rule in a rule set that has the earliest start time.
1055 #
1056 # Parameters:
1057 # remainingRules -- Rules to search
1058 # year - Year being processed.
1059 # stdGMTOffset - Current offset of standard time from GMT
1060 # DSTOffset - Current offset of daylight time from standard,
1061 # if daylight time is in effect.
1062 #
1063 # Results:
1064 # Returns the index in remainingRules of the next rule to
1065 # go into effect.
1066 #
1067 # Side effects:
1068 # None.
1069 #
1070 #----------------------------------------------------------------------
1071
1072 proc findEarliestRule {remainingRules year stdGMTOffset DSTOffset} {
1073 set earliest $::MAXWIDE
1074 set i 0
1075 foreach {
1076 fromYear toYear yearType monthIn daySpecOn timeAt save letter
1077 } $remainingRules {
1078 lappend daySpecOn $year $monthIn
1079 set dayIn [eval $daySpecOn]
1080 set secs [expr {wide(86400) * wide($dayIn) - 210866803200}]
1081 set secs [convertTimeOfDay $secs \
1082 $stdGMTOffset $DSTOffset {*}$timeAt]
1083 if {$secs < $earliest} {
1084 set earliest $secs
1085 set earliestIdx $i
1086 }
1087 incr i 8
1088 }
1089
1090 return [list $earliest $earliestIdx]
1091 }
1092
1093 #----------------------------------------------------------------------
1094 #
1095 # convertNamePattern --
1096 #
1097 # Converts a name pattern to the name of the time zone.
1098 #
1099 # Parameters:
1100 # pattern - Patthern to convert
1101 # flag - Daylight Time flag. An empty string denotes Standard
1102 # Time, anything else is Daylight Time.
1103 #
1104 # Results;
1105 # Returns the name of the time zone.
1106 #
1107 # Side effects:
1108 # None.
1109 #
1110 #----------------------------------------------------------------------
1111
1112 proc convertNamePattern {pattern flag} {
1113 if {[regexp {(.*)/(.*)} $pattern -> standard daylight]} {
1114 if {$flag ne ""} {
1115 set pattern $daylight
1116 } else {
1117 set pattern $standard
1118 }
1119 }
1120 return [string map [list %s $flag] $pattern]
1121 }
1122
1123 #----------------------------------------------------------------------
1124 #
1125 # convertTimeOfDay --
1126 #
1127 # Takes a time of day specifier from 'parseAt' and converts
1128 # to seconds from the Epoch,
1129 #
1130 # Parameters:
1131 # seconds -- Time at which the GMT day starts, in seconds
1132 # from the Posix epoch
1133 # stdGMTOffset - Offset of Standard Time from Greenwich
1134 # DSTOffset - Offset of Daylight Time from standard.
1135 # timeOfDay - Time of day to convert, in seconds from midnight
1136 # flag - Flag indicating whether the time is Greenwich, Standard
1137 # or wall-clock. (g, s, or w)
1138 #
1139 # Results:
1140 # Returns the time of day in seconds from the Posix epoch.
1141 #
1142 # Side effects:
1143 # None.
1144 #
1145 #----------------------------------------------------------------------
1146
1147 proc convertTimeOfDay {seconds stdGMTOffset DSTOffset timeOfDay flag} {
1148 incr seconds $timeOfDay
1149 switch -exact $flag {
1150 g - u - z {
1151 }
1152 w {
1153 incr seconds [expr {-$stdGMTOffset}]
1154 incr seconds [expr {-$DSTOffset}]
1155 }
1156 s {
1157 incr seconds [expr {-$stdGMTOffset}]
1158 }
1159 }
1160 return $seconds
1161 }
1162
1163 #----------------------------------------------------------------------
1164 #
1165 # processTimeZone --
1166 #
1167 # Generate the information about all time transitions in a
1168 # time zone.
1169 #
1170 # Parameters:
1171 # zoneName - Name of the time zone
1172 # zoneData - List containing the rows describing the time zone,
1173 # obtained from 'parseZone.
1174 #
1175 # Results:
1176 # Returns a list of rows. Each row consists of a time in
1177 # seconds from the Posix epoch, an offset from GMT to local
1178 # that begins at that time, a flag indicating whether DST
1179 # is in effect after that time, and the printable name of the
1180 # timezone that goes into effect at that time.
1181 #
1182 # Side effects:
1183 # None.
1184 #
1185 #----------------------------------------------------------------------
1186
1187 proc processTimeZone {zoneName zoneData} {
1188 set points {}
1189 set i 0
1190 foreach {startTime nextGMTOffset dstRule namePattern} $zoneData {
1191 incr i 4
1192 set until [lindex $zoneData $i]
1193 if {![info exists stdGMTOffset]} {
1194 set stdGMTOffset $nextGMTOffset
1195 }
1196 if {![info exists DSTOffset]} {
1197 set DSTOffset 0
1198 }
1199 if {$startTime eq "minimum"} {
1200 set secs $::MINWIDE
1201 set year 0
1202 } else {
1203 lassign $startTime year month dayRule timeOfDay
1204 lappend dayRule $year $month
1205 set startDay [eval $dayRule]
1206 set secs [expr {wide(86400) * wide($startDay) -210866803200}]
1207 set secs [convertTimeOfDay $secs \
1208 $stdGMTOffset $DSTOffset {*}$timeOfDay]
1209 }
1210 lappend dstRule \
1211 $year $secs $stdGMTOffset $DSTOffset $nextGMTOffset \
1212 $namePattern $until points
1213 lassign [eval $dstRule] stdGMTOffset DSTOffset
1214 }
1215 return $points
1216 }
1217
1218 #----------------------------------------------------------------------
1219 #
1220 # writeZones --
1221 #
1222 # Writes all the time zone information files.
1223 #
1224 # Parameters:
1225 # outDir - Directory in which to store the files.
1226 #
1227 # Results:
1228 # None.
1229 #
1230 # Side effects:
1231 # Writes the time zone information files; traces what's happening
1232 # on the standard output.
1233 #
1234 #----------------------------------------------------------------------
1235
1236 proc writeZones {outDir} {
1237 variable zones
1238
1239 # Walk the zones
1240
1241 foreach zoneName [lsort -dictionary [array names zones]] {
1242 puts "calculating: $zoneName"
1243 set fileName [eval [list file join $outDir] [file split $zoneName]]
1244
1245 # Create directories as needed
1246
1247 set dirName [file dirname $fileName]
1248 if {![file exists $dirName]} {
1249 puts "creating directory: $dirName"
1250 file mkdir $dirName
1251 }
1252
1253 # Generate data for a zone
1254
1255 set data ""
1256 set tzmapped {}
1257 foreach {
1258 time offset dst name
1259 } [processTimeZone $zoneName $zones($zoneName)] {
1260 if {$name eq "%z"} {
1261 # map %z to pure offset zone (e. g. offset -7200 -> -0200):
1262 set offmin [expr {abs($offset) / 60}]
1263 set name [format "%+03d%02d" [expr {
1264 ($offset < 0 ? -1 : 1) * ($offmin / 60)
1265 }] [expr {
1266 $offmin % 60
1267 }]
1268 ]
1269 if {![dict exists $tzmapped $offset]} { # output once per offs
1270 puts "\tmap %z ($offset) -> $name"
1271 dict set tzmapped $offset $name
1272 }
1273 }
1274 append data "\n " [list [list $time $offset $dst $name]]
1275 }
1276 append data \n
1277
1278 # Write the data to the information file
1279
1280 set f [open $fileName w]
1281 fconfigure $f -translation lf -encoding utf-8
1282 puts $f "\# created by $::argv0 - do not edit"
1283 puts $f ""
1284 puts $f [list set TZData(:$zoneName) $data]
1285 close $f
1286 }
1287
1288 return
1289 }
1290
1291 #----------------------------------------------------------------------
1292 #
1293 # writeLinks --
1294 #
1295 # Write files describing time zone synonyms (the Link directives
1296 # from the Olson files)
1297 #
1298 # Parameters:
1299 # outDir - Name of the directory where the output files go.
1300 #
1301 # Results:
1302 # None.
1303 #
1304 # Side effects:
1305 # Creates a file for each link.
1306
1307 proc writeLinks {outDir} {
1308 variable links
1309
1310 # Walk the links
1311
1312 foreach zoneName [lsort -dictionary [array names links]] {
1313 puts "creating link: $zoneName"
1314 set fileName [eval [list file join $outDir] [file split $zoneName]]
1315
1316 # Create directories as needed
1317
1318 set dirName [file dirname $fileName]
1319 if {![file exists $dirName]} {
1320 puts "creating directory: $dirName"
1321 file mkdir $dirName
1322 }
1323
1324 # Create code for the synonym
1325
1326 set linkTo $links($zoneName)
1327 set sourceCmd "\n [list LoadTimeZoneFile $linkTo]\n"
1328 set ifCmd [list if "!\[info exists TZData($linkTo)\]" $sourceCmd]
1329 set setCmd "set TZData(:$zoneName) \$TZData(:$linkTo)"
1330
1331 # Write the file
1332
1333 set f [open $fileName w]
1334 fconfigure $f -translation lf -encoding utf-8
1335 puts $f "\# created by $::argv0 - do not edit"
1336 puts $f $ifCmd
1337 puts $f $setCmd
1338 close $f
1339 }
1340
1341 return
1342 }
1343
1344 #----------------------------------------------------------------------
1345 #
1346 # MAIN PROGRAM
1347 #
1348 #----------------------------------------------------------------------
1349
1350 puts "Compiling time zones -- [clock format [clock seconds] \
1351 -format {%x %X} -locale system]"
1352
1353 # Determine directories
1354
1355 lassign $argv inDir outDir
1356
1357 puts "Olson files in $inDir"
1358 puts "Tcl files to be placed in $outDir"
1359
1360 # Initialize count of errors
1361
1362 set errorCount 0
1363
1364 # Parse the Olson files
1365
1366 loadFiles $inDir
1367 if {$errorCount > 0} {
1368 exit 1
1369 }
1370
1371 # Check that all riles appearing in Zone and Link lines actually exist
1372
1373 checkForwardRuleRefs
1374 if {$errorCount > 0} {
1375 exit 1
1376 }
1377
1378 # Write the time zone information files
1379
1380 writeZones $outDir
1381 writeLinks $outDir
1382 if {$errorCount > 0} {
1383 exit 1
1384 }
1385
1386 # All done!
1387
1388 exit