75c6d2a43136358aa34b5b58ecba6db51c5d9bd3
[gnulib.git] / lib / getdate.y
1 %{
2 /* Parse a string into an internal time stamp.
3    Copyright 1999 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Originally written by Steven M. Bellovin <smb@research.att.com> while
20    at the University of North Carolina at Chapel Hill.  Later tweaked by
21    a couple of people on Usenet.  Completely overhauled by Rich $alz
22    <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990.
23
24    Modified by Paul Eggert <eggert@twinsun.com> in August 1999 to do
25    the right thing about local DST.  Unlike previous versions, this
26    version is reentrant.  */
27
28 #ifdef HAVE_CONFIG_H
29 # include <config.h>
30 # ifdef HAVE_ALLOCA_H
31 #  include <alloca.h>
32 # endif
33 #endif
34
35 /* Since the code of getdate.y is not included in the Emacs executable
36    itself, there is no need to #define static in this file.  Even if
37    the code were included in the Emacs executable, it probably
38    wouldn't do any harm to #undef it here; this will only cause
39    problems if we try to write to a static variable, which I don't
40    think this code needs to do.  */
41 #ifdef emacs
42 # undef static
43 #endif
44
45 #include <ctype.h>
46
47 #if HAVE_STDLIB_H
48 # include <stdlib.h> /* for `free'; used by Bison 1.27 */
49 #endif
50
51 #if STDC_HEADERS || (! defined isascii && ! HAVE_ISASCII)
52 # define IN_CTYPE_DOMAIN(c) 1
53 #else
54 # define IN_CTYPE_DOMAIN(c) isascii (c)
55 #endif
56
57 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
58 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
59 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
60 #define ISDIGIT_LOCALE(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
61
62 /* ISDIGIT differs from ISDIGIT_LOCALE, as follows:
63    - Its arg may be any int or unsigned int; it need not be an unsigned char.
64    - It's guaranteed to evaluate its argument exactly once.
65    - It's typically faster.
66    Posix 1003.2-1992 section 2.5.2.1 page 50 lines 1556-1558 says that
67    only '0' through '9' are digits.  Prefer ISDIGIT to ISDIGIT_LOCALE unless
68    it's important to use the locale's definition of `digit' even when the
69    host does not conform to Posix.  */
70 #define ISDIGIT(c) ((unsigned) (c) - '0' <= 9)
71
72 #if STDC_HEADERS || HAVE_STRING_H
73 # include <string.h>
74 #endif
75
76 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
77 # define __attribute__(x)
78 #endif
79
80 #ifndef ATTRIBUTE_UNUSED
81 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
82 #endif
83
84 #define EPOCH_YEAR 1970
85 #define TM_YEAR_BASE 1900
86
87 #define HOUR(x) ((x) * 60)
88
89 /* An entry in the lexical lookup table.  */
90 typedef struct
91 {
92   char const *name;
93   int type;
94   int value;
95 } table;
96
97 /* Meridian: am, pm, or 24-hour style.  */
98 enum { MERam, MERpm, MER24 };
99
100 /* Information passed to and from the parser.  */
101 struct parser_control
102 {
103   /* The input string remaining to be parsed. */
104   const char *input;
105
106   /* N, if this is the Nth Tuesday.  */
107   int day_ordinal;
108
109   /* Day of week; Sunday is 0.  */
110   int day_number;
111
112   /* tm_isdst flag for the local zone.  */
113   int local_isdst;
114
115   /* Time zone, in minutes east of UTC.  */
116   int time_zone;
117
118   /* Style used for time.  */
119   int meridian;
120
121   /* Gregorian year, month, day, hour, minutes, and seconds.  */
122   int year;
123   int month;
124   int day;
125   int hour;
126   int minutes;
127   int seconds;
128
129   /* Relative year, month, day, hour, minutes, and seconds.  */
130   int rel_year;
131   int rel_month;
132   int rel_day;
133   int rel_hour;
134   int rel_minutes;
135   int rel_seconds;
136
137   /* Counts of nonterminals of various flavors parsed so far.  */
138   int dates_seen;
139   int days_seen;
140   int local_zones_seen;
141   int rels_seen;
142   int times_seen;
143   int zones_seen;
144
145   /* Table of local time zone abbrevations, terminated by a null entry.  */
146   table local_time_zone_table[3];
147 };
148
149 #define PC (* (struct parser_control *) parm)
150 #define YYLEX_PARAM parm
151 #define YYPARSE_PARAM parm
152 #define YYSTYPE int
153
154 static int yyerror ();
155 static int yylex ();
156
157 %}
158
159 /* We want a reentrant parser.  */
160 %pure_parser
161
162 /* This grammar has 13 shift/reduce conflicts. */
163 %expect 13
164
165 %token tAGO tDAY tDAY_UNIT tDAYZONE tDST tHOUR_UNIT tID
166 %token tLOCAL_ZONE tMERIDIAN tMINUTE_UNIT tMONTH tMONTH_UNIT
167 %token tSEC_UNIT tSNUMBER tUNUMBER tYEAR_UNIT tZONE
168
169 %%
170
171 spec:
172     /* empty */
173   | spec item
174   ;
175
176 item:
177     time
178       { PC.times_seen++; }
179   | local_zone
180       { PC.local_zones_seen++; }
181   | zone
182       { PC.zones_seen++; }
183   | date
184       { PC.dates_seen++; }
185   | day
186       { PC.days_seen++; }
187   | rel
188       { PC.rels_seen++; }
189   | number
190   ;
191
192 time:
193     tUNUMBER tMERIDIAN
194       {
195         PC.hour = $1;
196         PC.minutes = 0;
197         PC.seconds = 0;
198         PC.meridian = $2;
199       }
200   | tUNUMBER ':' tUNUMBER o_merid
201       {
202         PC.hour = $1;
203         PC.minutes = $3;
204         PC.seconds = 0;
205         PC.meridian = $4;
206       }
207   | tUNUMBER ':' tUNUMBER tSNUMBER
208       {
209         PC.hour = $1;
210         PC.minutes = $3;
211         PC.meridian = MER24;
212         PC.zones_seen++;
213         PC.time_zone = $4 % 100 + ($4 / 100) * 60;
214       }
215   | tUNUMBER ':' tUNUMBER ':' tUNUMBER o_merid
216       {
217         PC.hour = $1;
218         PC.minutes = $3;
219         PC.seconds = $5;
220         PC.meridian = $6;
221       }
222   | tUNUMBER ':' tUNUMBER ':' tUNUMBER tSNUMBER
223       {
224         PC.hour = $1;
225         PC.minutes = $3;
226         PC.seconds = $5;
227         PC.meridian = MER24;
228         PC.zones_seen++;
229         PC.time_zone = $6 % 100 + ($6 / 100) * 60;
230       }
231   ;
232
233 local_zone:
234     tLOCAL_ZONE
235       { PC.local_isdst = $1; }
236   | tLOCAL_ZONE tDST
237       { PC.local_isdst = $1 < 0 ? 1 : $1 + 1; }
238   ;
239
240 zone:
241     tZONE
242       { PC.time_zone = $1; }
243   | tDAYZONE
244       { PC.time_zone = $1 + 60; }
245   | tZONE tDST
246       { PC.time_zone = $1 + 60; }
247   ;
248
249 day:
250     tDAY
251       {
252         PC.day_ordinal = 1;
253         PC.day_number = $1;
254       }
255   | tDAY ','
256       {
257         PC.day_ordinal = 1;
258         PC.day_number = $1;
259       }
260   | tUNUMBER tDAY
261       {
262         PC.day_ordinal = $1;
263         PC.day_number = $2;
264       }
265   ;
266
267 date:
268     tUNUMBER '/' tUNUMBER
269       {
270         PC.month = $1;
271         PC.day = $3;
272       }
273   | tUNUMBER '/' tUNUMBER '/' tUNUMBER
274       {
275         /* Interpret as YYYY/MM/DD if 1000 <= $1, otherwise as MM/DD/YY.
276            The goal in recognizing YYYY/MM/DD is solely to support legacy
277            machine-generated dates like those in an RCS log listing.  If
278            you want portability, use the ISO 8601 format.  */
279         if (1000 <= $1)
280           {
281             PC.year = $1;
282             PC.month = $3;
283             PC.day = $5;
284           }
285         else
286           {
287             PC.month = $1;
288             PC.day = $3;
289             PC.year = $5;
290           }
291       }
292   | tUNUMBER tSNUMBER tSNUMBER
293       {
294         /* ISO 8601 format.  YYYY-MM-DD.  */
295         PC.year = $1;
296         PC.month = -$2;
297         PC.day = -$3;
298       }
299   | tUNUMBER tMONTH tSNUMBER
300       {
301         /* e.g. 17-JUN-1992.  */
302         PC.day = $1;
303         PC.month = $2;
304         PC.year = -$3;
305       }
306   | tMONTH tUNUMBER
307       {
308         PC.month = $1;
309         PC.day = $2;
310       }
311   | tMONTH tUNUMBER ',' tUNUMBER
312       {
313         PC.month = $1;
314         PC.day = $2;
315         PC.year = $4;
316       }
317   | tUNUMBER tMONTH
318       {
319         PC.month = $2;
320         PC.day = $1;
321       }
322   | tUNUMBER tMONTH tUNUMBER
323       {
324         PC.month = $2;
325         PC.day = $1;
326         PC.year = $3;
327       }
328   ;
329
330 rel:
331     relunit tAGO
332       {
333         PC.rel_seconds = -PC.rel_seconds;
334         PC.rel_minutes = -PC.rel_minutes;
335         PC.rel_hour = -PC.rel_hour;
336         PC.rel_day = -PC.rel_day;
337         PC.rel_month = -PC.rel_month;
338         PC.rel_year = -PC.rel_year;
339       }
340   | relunit
341   ;
342
343 relunit:
344     tUNUMBER tYEAR_UNIT
345       { PC.rel_year += $1 * $2; }
346   | tSNUMBER tYEAR_UNIT
347       { PC.rel_year += $1 * $2; }
348   | tYEAR_UNIT
349       { PC.rel_year += $1; }
350   | tUNUMBER tMONTH_UNIT
351       { PC.rel_month += $1 * $2; }
352   | tSNUMBER tMONTH_UNIT
353       { PC.rel_month += $1 * $2; }
354   | tMONTH_UNIT
355       { PC.rel_month += $1; }
356   | tUNUMBER tDAY_UNIT
357       { PC.rel_day += $1 * $2; }
358   | tSNUMBER tDAY_UNIT
359       { PC.rel_day += $1 * $2; }
360   | tDAY_UNIT
361       { PC.rel_day += $1; }
362   | tUNUMBER tHOUR_UNIT
363       { PC.rel_hour += $1 * $2; }
364   | tSNUMBER tHOUR_UNIT
365       { PC.rel_hour += $1 * $2; }
366   | tHOUR_UNIT
367       { PC.rel_hour += $1; }
368   | tUNUMBER tMINUTE_UNIT
369       { PC.rel_minutes += $1 * $2; }
370   | tSNUMBER tMINUTE_UNIT
371       { PC.rel_minutes += $1 * $2; }
372   | tMINUTE_UNIT
373       { PC.rel_minutes += $1; }
374   | tUNUMBER tSEC_UNIT
375       { PC.rel_seconds += $1 * $2; }
376   | tSNUMBER tSEC_UNIT
377       { PC.rel_seconds += $1 * $2; }
378   | tSEC_UNIT
379       { PC.rel_seconds += $1; }
380   ;
381
382 number:
383     tUNUMBER
384       {
385         if (PC.dates_seen && ! PC.rels_seen && (PC.times_seen || 100 <= $1))
386           PC.year = $1;
387         else
388           {
389             if (10000 < $1)
390               {
391                 PC.dates_seen++;
392                 PC.day = $1 % 100;
393                 PC.month = ($1 / 100) % 100;
394                 PC.year = $1 / 10000;
395               }
396             else
397               {
398                 PC.times_seen++;
399                 if ($1 < 100)
400                   {
401                     PC.hour = $1;
402                     PC.minutes = 0;
403                   }
404                 else
405                   {
406                     PC.hour = $1 / 100;
407                     PC.minutes = $1 % 100;
408                   }
409                 PC.seconds = 0;
410                 PC.meridian = MER24;
411               }
412           }
413       }
414   ;
415
416 o_merid:
417     /* empty */
418       { $$ = MER24; }
419   | tMERIDIAN
420       { $$ = $1; }
421   ;
422
423 %%
424
425 /* Include this file down here because bison inserts code above which
426    may define-away `const'.  We want the prototype for get_date to have
427    the same signature as the function definition.  */
428 #include "getdate.h"
429
430 #ifndef gmtime
431 struct tm *gmtime ();
432 #endif
433 #ifndef localtime
434 struct tm *localtime ();
435 #endif
436 #ifndef mktime
437 time_t mktime ();
438 #endif
439
440 static table const meridian_table[] =
441 {
442   { "AM",   tMERIDIAN, MERam },
443   { "A.M.", tMERIDIAN, MERam },
444   { "PM",   tMERIDIAN, MERpm },
445   { "P.M.", tMERIDIAN, MERpm },
446   { 0, 0, 0 }
447 };
448
449 static table const dst_table[] =
450 {
451   { "DST", tDST, 0 }
452 };
453
454 static table const month_and_day_table[] =
455 {
456   { "JANUARY",  tMONTH,  1 },
457   { "FEBRUARY", tMONTH,  2 },
458   { "MARCH",    tMONTH,  3 },
459   { "APRIL",    tMONTH,  4 },
460   { "MAY",      tMONTH,  5 },
461   { "JUNE",     tMONTH,  6 },
462   { "JULY",     tMONTH,  7 },
463   { "AUGUST",   tMONTH,  8 },
464   { "SEPTEMBER",tMONTH,  9 },
465   { "SEPT",     tMONTH,  9 },
466   { "OCTOBER",  tMONTH, 10 },
467   { "NOVEMBER", tMONTH, 11 },
468   { "DECEMBER", tMONTH, 12 },
469   { "SUNDAY",   tDAY,    0 },
470   { "MONDAY",   tDAY,    1 },
471   { "TUESDAY",  tDAY,    2 },
472   { "TUES",     tDAY,    2 },
473   { "WEDNESDAY",tDAY,    3 },
474   { "WEDNES",   tDAY,    3 },
475   { "THURSDAY", tDAY,    4 },
476   { "THUR",     tDAY,    4 },
477   { "THURS",    tDAY,    4 },
478   { "FRIDAY",   tDAY,    5 },
479   { "SATURDAY", tDAY,    6 },
480   { 0, 0, 0 }
481 };
482
483 static table const time_units_table[] =
484 {
485   { "YEAR",     tYEAR_UNIT,      1 },
486   { "MONTH",    tMONTH_UNIT,     1 },
487   { "FORTNIGHT",tDAY_UNIT,      14 },
488   { "WEEK",     tDAY_UNIT,       7 },
489   { "DAY",      tDAY_UNIT,       1 },
490   { "HOUR",     tHOUR_UNIT,      1 },
491   { "MINUTE",   tMINUTE_UNIT,    1 },
492   { "MIN",      tMINUTE_UNIT,    1 },
493   { "SECOND",   tSEC_UNIT,       1 },
494   { "SEC",      tSEC_UNIT,       1 },
495   { 0, 0, 0 }
496 };
497
498 /* Assorted relative-time words. */
499 static table const relative_time_table[] =
500 {
501   { "TOMORROW", tMINUTE_UNIT,   24 * 60 },
502   { "YESTERDAY",tMINUTE_UNIT,   - (24 * 60) },
503   { "TODAY",    tMINUTE_UNIT,    0 },
504   { "NOW",      tMINUTE_UNIT,    0 },
505   { "LAST",     tUNUMBER,       -1 },
506   { "THIS",     tUNUMBER,        0 },
507   { "NEXT",     tUNUMBER,        1 },
508   { "FIRST",    tUNUMBER,        1 },
509 /*{ "SECOND",   tUNUMBER,        2 }, */
510   { "THIRD",    tUNUMBER,        3 },
511   { "FOURTH",   tUNUMBER,        4 },
512   { "FIFTH",    tUNUMBER,        5 },
513   { "SIXTH",    tUNUMBER,        6 },
514   { "SEVENTH",  tUNUMBER,        7 },
515   { "EIGHTH",   tUNUMBER,        8 },
516   { "NINTH",    tUNUMBER,        9 },
517   { "TENTH",    tUNUMBER,       10 },
518   { "ELEVENTH", tUNUMBER,       11 },
519   { "TWELFTH",  tUNUMBER,       12 },
520   { "AGO",      tAGO,            1 },
521   { 0, 0, 0 }
522 };
523
524 /* The time zone table.  This table is necessarily incomplete, as time
525    zone abbreviations are ambiguous; e.g. Australians interpret "EST"
526    as Eastern time in Australia, not as US Eastern Standard Time.
527    You cannot rely on getdate to handle arbitrary time zone
528    abbreviations; use numeric abbreviations like `-0500' instead.  */
529 static table const time_zone_table[] =
530 {
531   { "GMT",      tZONE,     HOUR ( 0) }, /* Greenwich Mean */
532   { "UT",       tZONE,     HOUR ( 0) }, /* Universal (Coordinated) */
533   { "UTC",      tZONE,     HOUR ( 0) },
534   { "WET",      tZONE,     HOUR ( 0) }, /* Western European */
535   { "WEST",     tDAYZONE,  HOUR ( 0) }, /* Western European Summer */
536   { "BST",      tDAYZONE,  HOUR ( 0) }, /* British Summer */
537   { "ART",      tZONE,    -HOUR ( 3) }, /* Argentina */
538   { "BRT",      tZONE,    -HOUR ( 3) }, /* Brazil */
539   { "BRST",     tDAYZONE, -HOUR ( 3) }, /* Brazil Summer */
540   { "NST",      tZONE,   -(HOUR ( 3) + 30) },   /* Newfoundland Standard */
541   { "NDT",      tDAYZONE,-(HOUR ( 3) + 30) },   /* Newfoundland Daylight */
542   { "AST",      tZONE,    -HOUR ( 4) }, /* Atlantic Standard */
543   { "ADT",      tDAYZONE, -HOUR ( 4) }, /* Atlantic Daylight */
544   { "CLT",      tZONE,    -HOUR ( 4) }, /* Chile */
545   { "CLST",     tDAYZONE, -HOUR ( 4) }, /* Chile Summer */
546   { "EST",      tZONE,    -HOUR ( 5) }, /* Eastern Standard */
547   { "EDT",      tDAYZONE, -HOUR ( 5) }, /* Eastern Daylight */
548   { "CST",      tZONE,    -HOUR ( 6) }, /* Central Standard */
549   { "CDT",      tDAYZONE, -HOUR ( 6) }, /* Central Daylight */
550   { "MST",      tZONE,    -HOUR ( 7) }, /* Mountain Standard */
551   { "MDT",      tDAYZONE, -HOUR ( 7) }, /* Mountain Daylight */
552   { "PST",      tZONE,    -HOUR ( 8) }, /* Pacific Standard */
553   { "PDT",      tDAYZONE, -HOUR ( 8) }, /* Pacific Daylight */
554   { "AKST",     tZONE,    -HOUR ( 9) }, /* Alaska Standard */
555   { "AKDT",     tDAYZONE, -HOUR ( 9) }, /* Alaska Daylight */
556   { "HST",      tZONE,    -HOUR (10) }, /* Hawaii Standard */
557   { "HAST",     tZONE,    -HOUR (10) }, /* Hawaii-Aleutian Standard */
558   { "HADT",     tDAYZONE, -HOUR (10) }, /* Hawaii-Aleutian Daylight */
559   { "SST",      tZONE,    -HOUR (12) }, /* Samoa Standard */
560   { "WAT",      tZONE,     HOUR ( 1) }, /* West Africa */
561   { "CET",      tZONE,     HOUR ( 1) }, /* Central European */
562   { "CEST",     tDAYZONE,  HOUR ( 1) }, /* Central European Summer */
563   { "MET",      tZONE,     HOUR ( 1) }, /* Middle European */
564   { "MEZ",      tZONE,     HOUR ( 1) }, /* Middle European */
565   { "MEST",     tDAYZONE,  HOUR ( 1) }, /* Middle European Summer */
566   { "MESZ",     tDAYZONE,  HOUR ( 1) }, /* Middle European Summer */
567   { "EET",      tZONE,     HOUR ( 2) }, /* Eastern European */
568   { "EEST",     tDAYZONE,  HOUR ( 2) }, /* Eastern European Summer */
569   { "CAT",      tZONE,     HOUR ( 2) }, /* Central Africa */
570   { "SAST",     tZONE,     HOUR ( 2) }, /* South Africa Standard */
571   { "EAT",      tZONE,     HOUR ( 3) }, /* East Africa */
572   { "MSK",      tZONE,     HOUR ( 3) }, /* Moscow */
573   { "MSD",      tDAYZONE,  HOUR ( 3) }, /* Moscow Daylight */
574   { "IST",      tZONE,    (HOUR ( 5) + 30) },   /* India Standard */
575   { "SGT",      tZONE,     HOUR ( 8) }, /* Singapore */
576   { "KST",      tZONE,     HOUR ( 9) }, /* Korea Standard */
577   { "JST",      tZONE,     HOUR ( 9) }, /* Japan Standard */
578   { "GST",      tZONE,     HOUR (10) }, /* Guam Standard */
579   { "NZST",     tZONE,     HOUR (12) }, /* New Zealand Standard */
580   { "NZDT",     tDAYZONE,  HOUR (12) }, /* New Zealand Daylight */
581   { 0, 0, 0  }
582 };
583
584 /* Military time zone table. */
585 static table const military_table[] =
586 {
587   { "A", tZONE, -HOUR ( 1) },
588   { "B", tZONE, -HOUR ( 2) },
589   { "C", tZONE, -HOUR ( 3) },
590   { "D", tZONE, -HOUR ( 4) },
591   { "E", tZONE, -HOUR ( 5) },
592   { "F", tZONE, -HOUR ( 6) },
593   { "G", tZONE, -HOUR ( 7) },
594   { "H", tZONE, -HOUR ( 8) },
595   { "I", tZONE, -HOUR ( 9) },
596   { "K", tZONE, -HOUR (10) },
597   { "L", tZONE, -HOUR (11) },
598   { "M", tZONE, -HOUR (12) },
599   { "N", tZONE,  HOUR ( 1) },
600   { "O", tZONE,  HOUR ( 2) },
601   { "P", tZONE,  HOUR ( 3) },
602   { "Q", tZONE,  HOUR ( 4) },
603   { "R", tZONE,  HOUR ( 5) },
604   { "S", tZONE,  HOUR ( 6) },
605   { "T", tZONE,  HOUR ( 7) },
606   { "U", tZONE,  HOUR ( 8) },
607   { "V", tZONE,  HOUR ( 9) },
608   { "W", tZONE,  HOUR (10) },
609   { "X", tZONE,  HOUR (11) },
610   { "Y", tZONE,  HOUR (12) },
611   { "Z", tZONE,  HOUR ( 0) },
612   { 0, 0, 0 }
613 };
614
615 \f
616
617 static int
618 to_hour (int hours, int meridian)
619 {
620   switch (meridian)
621     {
622     case MER24:
623       return 0 <= hours && hours < 24 ? hours : -1;
624     case MERam:
625       return 0 < hours && hours < 12 ? hours : hours == 12 ? 0 : -1;
626     case MERpm:
627       return 0 < hours && hours < 12 ? hours + 12 : hours == 12 ? 12 : -1;
628     default:
629       abort ();
630     }
631   /* NOTREACHED */
632 }
633
634 static int
635 to_year (int year)
636 {
637   if (year < 0)
638     year = -year;
639
640   /* XPG4 suggests that years 00-68 map to 2000-2068, and
641      years 69-99 map to 1969-1999.  */
642   if (year < 69)
643     year += 2000;
644   else if (year < 100)
645     year += 1900;
646
647   return year;
648 }
649
650 static table const *
651 lookup_zone (struct parser_control const *pc, char const *name)
652 {
653   table const *tp;
654
655   /* Try local zone abbreviations first; they're more likely to be right.  */
656   for (tp = pc->local_time_zone_table; tp->name; tp++)
657     if (strcmp (name, tp->name) == 0)
658       return tp;
659
660   for (tp = time_zone_table; tp->name; tp++)
661     if (strcmp (name, tp->name) == 0)
662       return tp;
663
664   return 0;
665 }
666
667 #if ! HAVE_TM_GMTOFF
668 /* Yield the difference between *A and *B,
669    measured in seconds, ignoring leap seconds.
670    The body of this function is taken directly from the GNU C Library;
671    see src/strftime.c.  */
672 static int
673 tm_diff (struct tm const *a, struct tm const *b)
674 {
675   /* Compute intervening leap days correctly even if year is negative.
676      Take care to avoid int overflow in leap day calculations,
677      but it's OK to assume that A and B are close to each other.  */
678   int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
679   int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
680   int a100 = a4 / 25 - (a4 % 25 < 0);
681   int b100 = b4 / 25 - (b4 % 25 < 0);
682   int a400 = a100 >> 2;
683   int b400 = b100 >> 2;
684   int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
685   int years = a->tm_year - b->tm_year;
686   int days = (365 * years + intervening_leap_days
687               + (a->tm_yday - b->tm_yday));
688   return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
689                 + (a->tm_min - b->tm_min))
690           + (a->tm_sec - b->tm_sec));
691 }
692 #endif /* ! HAVE_TM_GMTOFF */
693
694 static table const *
695 lookup_word (struct parser_control const *pc, char *word)
696 {
697   char *p;
698   char *q;
699   size_t wordlen;
700   table const *tp;
701   int i;
702   int abbrev;
703
704   /* Make it uppercase.  */
705   for (p = word; *p; p++)
706     if (ISLOWER ((unsigned char) *p))
707       *p = toupper ((unsigned char) *p);
708
709   for (tp = meridian_table; tp->name; tp++)
710     if (strcmp (word, tp->name) == 0)
711       return tp;
712
713   /* See if we have an abbreviation for a month. */
714   wordlen = strlen (word);
715   abbrev = wordlen == 3 || (wordlen == 4 && word[3] == '.');
716
717   for (tp = month_and_day_table; tp->name; tp++)
718     if ((abbrev ? strncmp (word, tp->name, 3) : strcmp (word, tp->name)) == 0)
719       return tp;
720
721   if ((tp = lookup_zone (pc, word)))
722     return tp;
723
724   if (strcmp (word, dst_table[0].name) == 0)
725     return dst_table;
726
727   for (tp = time_units_table; tp->name; tp++)
728     if (strcmp (word, tp->name) == 0)
729       return tp;
730
731   /* Strip off any plural and try the units table again. */
732   if (word[wordlen - 1] == 'S')
733     {
734       word[wordlen - 1] = '\0';
735       for (tp = time_units_table; tp->name; tp++)
736         if (strcmp (word, tp->name) == 0)
737           return tp;
738       word[wordlen - 1] = 'S';  /* For "this" in relative_time_table.  */
739     }
740
741   for (tp = relative_time_table; tp->name; tp++)
742     if (strcmp (word, tp->name) == 0)
743       return tp;
744
745   /* Military time zones. */
746   if (wordlen == 1)
747     for (tp = military_table; tp->name; tp++)
748       if (word[0] == tp->name[0])
749         return tp;
750
751   /* Drop out any periods and try the time zone table again. */
752   for (i = 0, p = q = word; (*p = *q); q++)
753     if (*q == '.')
754       i = 1;
755     else
756       p++;
757   if (i && (tp = lookup_zone (pc, word)))
758     return tp;
759
760   return 0;
761 }
762
763 static int
764 yylex (YYSTYPE *lvalp, struct parser_control *pc)
765 {
766   unsigned char c;
767   int count;
768
769   for (;;)
770     {
771       while (c = *pc->input, ISSPACE (c))
772         pc->input++;
773
774       if (ISDIGIT (c) || c == '-' || c == '+')
775         {
776           int sign;
777           if (c == '-' || c == '+')
778             {
779               sign = c == '-' ? -1 : 1;
780               if (! ISDIGIT (*++pc->input))
781                 /* skip the '-' sign */
782                 continue;
783             }
784           else
785             sign = 0;
786           for (*lvalp = 0; ISDIGIT (c = *pc->input++);)
787             *lvalp = 10 * *lvalp + (c - '0');
788           pc->input--;
789           if (sign < 0)
790             *lvalp = - *lvalp;
791           return sign ? tSNUMBER : tUNUMBER;
792         }
793
794       if (ISALPHA (c))
795         {
796           char buff[20];
797           char *p = buff;
798           table const *tp;
799
800           do
801             {
802               if (p < buff + sizeof buff - 1)
803                 *p++ = c;
804               c = *++pc->input;
805             }
806           while (ISALPHA (c) || c == '.');
807
808           *p = '\0';
809           tp = lookup_word (pc, buff);
810           if (! tp)
811             return tID;
812           *lvalp = tp->value;
813           return tp->type;
814         }
815
816       if (c != '(')
817         return *pc->input++;
818       count = 0;
819       do
820         {
821           c = *pc->input++;
822           if (c == '\0')
823             return c;
824           if (c == '(')
825             count++;
826           else if (c == ')')
827             count--;
828         }
829       while (count > 0);
830     }
831 }
832
833 /* Do nothing if the parser reports an error.  */
834 static int
835 yyerror (char *s ATTRIBUTE_UNUSED)
836 {
837   return 0;
838 }
839
840 /* Parse a date/time string P.  Return the corresponding time_t value,
841    or (time_t) -1 if there is an error.  P can be an incomplete or
842    relative time specification; if so, use *NOW as the basis for the
843    returned time.  */
844 time_t
845 get_date (const char *p, const time_t *now)
846 {
847   time_t Start = now ? *now : time (0);
848   struct tm *tmp = localtime (&Start);
849   struct tm tm;
850   struct tm tm0;
851   struct parser_control pc;
852
853   if (! tmp)
854     return -1;
855
856   pc.input = p;
857   pc.year = tmp->tm_year + TM_YEAR_BASE;
858   pc.month = tmp->tm_mon + 1;
859   pc.day = tmp->tm_mday;
860   pc.hour = tmp->tm_hour;
861   pc.minutes = tmp->tm_min;
862   pc.seconds = tmp->tm_sec;
863   tm.tm_isdst = tmp->tm_isdst;
864
865   pc.meridian = MER24;
866   pc.rel_seconds = 0;
867   pc.rel_minutes = 0;
868   pc.rel_hour = 0;
869   pc.rel_day = 0;
870   pc.rel_month = 0;
871   pc.rel_year = 0;
872   pc.dates_seen = 0;
873   pc.days_seen = 0;
874   pc.rels_seen = 0;
875   pc.times_seen = 0;
876   pc.local_zones_seen = 0;
877   pc.zones_seen = 0;
878
879 #if HAVE_TM_ZONE
880   pc.local_time_zone_table[0].name = tmp->tm_zone;
881   pc.local_time_zone_table[0].type = tLOCAL_ZONE;
882   pc.local_time_zone_table[0].value = tmp->tm_isdst;
883   pc.local_time_zone_table[1].name = 0;
884
885   /* Probe the names used in the next three calendar quarters, looking
886      for a tm_isdst different from the one we already have.  */
887   {
888     int quarter;
889     for (quarter = 1; quarter <= 3; quarter++)
890       {
891         time_t probe = Start + quarter * (90 * 24 * 60 * 60);
892         struct tm *probe_tm = localtime (&probe);
893         if (probe_tm && probe_tm->tm_zone
894             && probe_tm->tm_isdst != pc.local_time_zone_table[0].value)
895           {
896               {
897                 pc.local_time_zone_table[1].name = probe_tm->tm_zone;
898                 pc.local_time_zone_table[1].type = tLOCAL_ZONE;
899                 pc.local_time_zone_table[1].value = probe_tm->tm_isdst;
900                 pc.local_time_zone_table[2].name = 0;
901               }
902             break;
903           }
904       }
905   }
906 #else
907 #if HAVE_TZNAME
908   {
909 # ifndef tzname
910     extern char *tzname[];
911 # endif
912     int i;
913     for (i = 0; i < 2; i++)
914       {
915         pc.local_time_zone_table[i].name = tzname[i];
916         pc.local_time_zone_table[i].type = tLOCAL_ZONE;
917         pc.local_time_zone_table[i].value = i;
918       }
919     pc.local_time_zone_table[i].name = 0;
920   }
921 #else
922   pc.local_time_zone_table[0].name = 0;
923 #endif
924 #endif
925
926   if (pc.local_time_zone_table[0].name && pc.local_time_zone_table[1].name
927       && ! strcmp (pc.local_time_zone_table[0].name,
928                    pc.local_time_zone_table[1].name))
929     {
930       /* This locale uses the same abbrevation for standard and
931          daylight times.  So if we see that abbreviation, we don't
932          know whether it's daylight time.  */
933       pc.local_time_zone_table[0].value = -1;
934       pc.local_time_zone_table[1].name = 0;
935     }
936
937   if (yyparse (&pc) != 0
938       || 1 < pc.times_seen || 1 < pc.dates_seen || 1 < pc.days_seen
939       || 1 < (pc.local_zones_seen + pc.zones_seen)
940       || (pc.local_zones_seen && 1 < pc.local_isdst))
941     return -1;
942
943   tm.tm_year = to_year (pc.year) - TM_YEAR_BASE + pc.rel_year;
944   tm.tm_mon = pc.month - 1 + pc.rel_month;
945   tm.tm_mday = pc.day + pc.rel_day;
946   if (pc.times_seen || (pc.rels_seen && ! pc.dates_seen && ! pc.days_seen))
947     {
948       tm.tm_hour = to_hour (pc.hour, pc.meridian);
949       if (tm.tm_hour < 0)
950         return -1;
951       tm.tm_min = pc.minutes;
952       tm.tm_sec = pc.seconds;
953     }
954   else
955     {
956       tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
957     }
958   tm.tm_hour += pc.rel_hour;
959   tm.tm_min += pc.rel_minutes;
960   tm.tm_sec += pc.rel_seconds;
961
962   /* Let mktime deduce tm_isdst if we have an absolute time stamp,
963      or if the relative time stamp mentions days, months, or years.  */
964   if (pc.dates_seen | pc.days_seen | pc.times_seen | pc.rel_day | pc.rel_month | pc.rel_year)
965     tm.tm_isdst = -1;
966
967   /* But if the input explicitly specifies local time with or without
968      DST, give mktime that information.  */
969   if (pc.local_zones_seen)
970     tm.tm_isdst = pc.local_isdst;
971
972   tm0 = tm;
973
974   Start = mktime (&tm);
975
976   if (Start == (time_t) -1)
977     {
978
979       /* Guard against falsely reporting errors near the time_t boundaries
980          when parsing times in other time zones.  For example, if the min
981          time_t value is 1970-01-01 00:00:00 UTC and we are 8 hours ahead
982          of UTC, then the min localtime value is 1970-01-01 08:00:00; if
983          we apply mktime to 1970-01-01 00:00:00 we will get an error, so
984          we apply mktime to 1970-01-02 08:00:00 instead and adjust the time
985          zone by 24 hours to compensate.  This algorithm assumes that
986          there is no DST transition within a day of the time_t boundaries.  */
987       if (pc.zones_seen)
988         {
989           tm = tm0;
990           if (tm.tm_year <= EPOCH_YEAR - TM_YEAR_BASE)
991             {
992               tm.tm_mday++;
993               pc.time_zone += 24 * 60;
994             }
995           else
996             {
997               tm.tm_mday--;
998               pc.time_zone -= 24 * 60;
999             }
1000           Start = mktime (&tm);
1001         }
1002
1003       if (Start == (time_t) -1)
1004         return Start;
1005     }
1006
1007   if (pc.days_seen && ! pc.dates_seen)
1008     {
1009       tm.tm_mday += ((pc.day_number - tm.tm_wday + 7) % 7
1010                      + 7 * (pc.day_ordinal - (0 < pc.day_ordinal)));
1011       Start = mktime (&tm);
1012       if (Start == (time_t) -1)
1013         return Start;
1014     }
1015
1016   if (pc.zones_seen)
1017     {
1018       int delta = pc.time_zone * 60;
1019 #ifdef HAVE_TM_GMTOFF
1020       delta -= tm.tm_gmtoff;
1021 #else
1022       struct tm *gmt = gmtime (&Start);
1023       if (! gmt)
1024         return -1;
1025       delta -= tm_diff (&tm, gmt);
1026 #endif
1027       if ((Start < Start - delta) != (delta < 0))
1028         return -1;      /* time_t overflow */
1029       Start -= delta;
1030     }
1031
1032   return Start;
1033 }
1034
1035 #if TEST
1036
1037 #include <stdio.h>
1038
1039 int
1040 main (int ac, char **av)
1041 {
1042   char buff[BUFSIZ];
1043   time_t d;
1044
1045   printf ("Enter date, or blank line to exit.\n\t> ");
1046   fflush (stdout);
1047
1048   buff[BUFSIZ - 1] = 0;
1049   while (fgets (buff, BUFSIZ - 1, stdin) && buff[0])
1050     {
1051       d = get_date (buff, 0);
1052       if (d == (time_t) -1)
1053         printf ("Bad format - couldn't convert.\n");
1054       else
1055         printf ("%s", ctime (&d));
1056       printf ("\t> ");
1057       fflush (stdout);
1058     }
1059   return 0;
1060 }
1061 #endif /* defined TEST */