Rewrite formatted data input routines to conform to SPSS data formats
[pspp-builds.git] / src / data / data-in.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    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
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21
22 #include "data-in.h"
23
24 #include <ctype.h>
25 #include <errno.h>
26 #include <math.h>
27 #include <stdarg.h>
28 #include <stddef.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdbool.h>
33
34 #include "calendar.h"
35 #include "identifier.h"
36 #include "settings.h"
37 #include "variable.h"
38
39 #include <libpspp/assertion.h>
40 #include <libpspp/compiler.h>
41 #include <libpspp/integer-format.h>
42 #include <libpspp/magic.h>
43 #include <libpspp/message.h>
44 #include <libpspp/misc.h>
45 #include <libpspp/str.h>
46
47 #include "c-ctype.h"
48 #include "minmax.h"
49 #include "size_max.h"
50 #include "xalloc.h"
51
52 #include "gettext.h"
53 #define _(msgid) gettext (msgid)
54 \f
55 /* Information about parsing one data field. */
56 struct data_in
57   {
58     struct substring input;     /* Source. */
59     enum fmt_type format;       /* Input format. */
60     int implied_decimals;       /* Number of implied decimal places. */
61
62     union value *output;        /* Destination. */
63     int width;                  /* Output width. */
64
65     int first_column;           /* First column of field; 0 if inapplicable. */
66     int last_column;            /* Last column. */
67   };
68
69 /* Integer format used for IB and PIB input. */
70 static enum integer_format input_integer_format = INTEGER_NATIVE;
71
72 /* Floating-point format used for RB and RBHEX input. */
73 static enum float_format input_float_format = FLOAT_NATIVE_DOUBLE;
74
75 typedef bool data_in_parser_func (struct data_in *);
76 #define FMT(NAME, METHOD, IMIN, OMIN, IO, CATEGORY) \
77         static data_in_parser_func parse_##METHOD;
78 #include "format.def"
79
80 static void vdata_warning (const struct data_in *, const char *, va_list)
81      PRINTF_FORMAT (2, 0);
82 static void data_warning (const struct data_in *, const char *, ...)
83      PRINTF_FORMAT (2, 3);
84
85 static void apply_implied_decimals (struct data_in *);
86 static void default_result (struct data_in *);
87 static bool trim_spaces_and_check_missing (struct data_in *);
88
89 static int hexit_value (int c);
90 \f
91 /* Parses the characters in INPUT according to FORMAT.  Stores
92    the parsed representation in OUTPUT, which has the given WIDTH
93    (0 for a numeric field, otherwise the string width).
94
95    If no decimal point is included in a numeric format, then
96    IMPLIED_DECIMALS decimal places are implied.  Specify 0 if no
97    decimal places should be implied.
98
99    If FIRST_COLUMN is nonzero, then it should be the 1-based
100    column number of the first character in INPUT, used in error
101    messages. */
102 bool
103 data_in (struct substring input, 
104          enum fmt_type format, int implied_decimals,
105          int first_column, union value *output, int width) 
106 {
107   static data_in_parser_func *const handlers[FMT_NUMBER_OF_FORMATS] = 
108     {
109 #define FMT(NAME, METHOD, IMIN, OMIN, IO, CATEGORY) parse_##METHOD,
110 #include "format.def"
111     };
112
113   struct data_in i;
114   bool ok;
115
116   assert ((width != 0) == fmt_is_string (format));
117
118   i.input = input;
119   i.format = format;
120   i.implied_decimals = implied_decimals;
121
122   i.output = output;
123   i.width = width;
124
125   i.first_column = first_column;
126   i.last_column = first_column + ss_length (input) - 1;
127
128   if (!ss_is_empty (i.input)) 
129     {
130       ok = handlers[i.format] (&i); 
131       if (!ok)
132         default_result (&i);
133     }
134   else
135     {
136       default_result (&i);
137       ok = true;
138     }
139
140   return ok;
141 }
142
143 /* Returns the integer format used for IB and PIB input. */
144 enum integer_format
145 data_in_get_integer_format (void) 
146 {
147   return input_integer_format;
148 }
149
150 /* Sets the integer format used for IB and PIB input to
151    FORMAT. */
152 void
153 data_in_set_integer_format (enum integer_format format) 
154 {
155   input_integer_format = format;
156 }
157
158 /* Returns the floating-point format used for RB and RBHEX
159    input. */
160 enum float_format
161 data_in_get_float_format (void) 
162 {
163   return input_float_format;
164 }
165
166 /* Sets the floating-point format used for RB and RBHEX input to
167    FORMAT. */
168 void
169 data_in_set_float_format (enum float_format format) 
170 {
171   input_float_format = format;
172 }
173 \f
174 /* Format parsers. */ 
175
176 /* Parses F, COMMA, DOT, DOLLAR, PCT, and E input formats. */
177 static bool
178 parse_number (struct data_in *i)
179 {
180   const struct fmt_number_style *style = fmt_get_style (i->format);
181
182   struct string tmp;
183
184   bool explicit_decimals = false;
185   int save_errno;
186   char *tail;
187
188   assert (fmt_get_category (i->format) != FMT_CAT_CUSTOM);
189
190   /* Trim spaces and check for missing value representation. */
191   if (trim_spaces_and_check_missing (i))
192     return true;
193
194   ds_init_empty (&tmp);
195   ds_extend (&tmp, 64);
196   
197   /* Prefix character may precede sign. */
198   if (!ss_is_empty (style->prefix)) 
199     {
200       ss_match_char (&i->input, ss_first (style->prefix));
201       ss_ltrim (&i->input, ss_cstr (CC_SPACES));
202     }
203
204   /* Sign. */
205   if (ss_match_char (&i->input, '-')) 
206     {
207       ds_put_char (&tmp, '-');
208       ss_ltrim (&i->input, ss_cstr (CC_SPACES));
209     }
210   else 
211     {
212       ss_match_char (&i->input, '+');
213       ss_ltrim (&i->input, ss_cstr (CC_SPACES));
214     }
215
216   /* Prefix character may follow sign. */
217   if (!ss_is_empty (style->prefix)) 
218     {
219       ss_match_char (&i->input, ss_first (style->prefix));
220       ss_ltrim (&i->input, ss_cstr (CC_SPACES));
221     }
222
223   /* Digits before decimal point. */
224   while (c_isdigit (ss_first (i->input)))
225     {
226       ds_put_char (&tmp, ss_get_char (&i->input));
227       if (style->grouping != 0)
228         ss_match_char (&i->input, style->grouping);
229     }
230
231   /* Decimal point and following digits. */
232   if (ss_match_char (&i->input, style->decimal)) 
233     {
234       explicit_decimals = true;
235       ds_put_char (&tmp, '.');
236       while (c_isdigit (ss_first (i->input)))
237         ds_put_char (&tmp, ss_get_char (&i->input));
238     }
239
240   /* Exponent. */
241   if (!ds_is_empty (&tmp)
242       && !ss_is_empty (i->input)
243       && strchr ("eEdD-+", ss_first (i->input)))
244     {
245       explicit_decimals = true;
246       ds_put_char (&tmp, 'e');
247
248       if (strchr ("eEdD", ss_first (i->input))) 
249         {
250           ss_advance (&i->input, 1);
251           ss_match_char (&i->input, ' ');
252         }
253
254       if (ss_first (i->input) == '-' || ss_first (i->input) == '+')
255         {
256           if (ss_get_char (&i->input) == '-')
257             ds_put_char (&tmp, '-');
258           ss_match_char (&i->input, ' ');
259         }
260
261       while (c_isdigit (ss_first (i->input)))
262         ds_put_char (&tmp, ss_get_char (&i->input));
263     }
264
265   /* Suffix character. */
266   if (!ss_is_empty (style->suffix))
267     ss_match_char (&i->input, ss_first (style->suffix));
268
269   if (!ss_is_empty (i->input))
270     {
271       if (ds_is_empty (&tmp))
272         data_warning (i, _("Field contents are not numeric."));
273       else
274         data_warning (i, _("Number followed by garbage."));
275       ds_destroy (&tmp);
276       return false;
277     }
278
279   /* Let strtod() do the conversion. */
280   save_errno = errno;
281   errno = 0;
282   i->output->f = strtod (ds_cstr (&tmp), &tail);
283   if (*tail != '\0')
284     {
285       data_warning (i, _("Invalid numeric syntax."));
286       errno = save_errno;
287       ds_destroy (&tmp);
288       return false;
289     }
290   else if (errno == ERANGE) 
291     {
292       if (fabs (i->output->f) > 1)
293         {
294           data_warning (i, _("Too-large number set to system-missing."));
295           i->output->f = SYSMIS;
296         }
297       else 
298         {
299           data_warning (i, _("Too-small number set to zero."));
300           i->output->f = 0.0; 
301         }
302     }
303   else 
304     {
305       errno = save_errno;
306       if (!explicit_decimals)
307         apply_implied_decimals (i);
308     }
309
310   ds_destroy (&tmp);
311   return true;
312 }
313
314 /* Parses N format. */
315 static bool
316 parse_N (struct data_in *i)
317 {
318   int c;
319
320   i->output->f = 0;
321   while ((c = ss_get_char (&i->input)) != EOF) 
322     {
323       if (!c_isdigit (c))
324         {
325           data_warning (i, _("All characters in field must be digits."));
326           return false;
327         }
328       i->output->f = i->output->f * 10.0 + (c - '0'); 
329     }
330
331   apply_implied_decimals (i);
332   return true;
333 }
334
335 /* Parses PIBHEX format. */
336 static bool
337 parse_PIBHEX (struct data_in *i)
338 {
339   double n;
340   int c;
341
342   n = 0.0;
343
344   while ((c = ss_get_char (&i->input)) != EOF)
345     {
346       if (!c_isxdigit (c))
347         {
348           data_warning (i, _("Unrecognized character in field."));
349           return false;
350         }
351       n = n * 16.0 + hexit_value (c);
352     }
353   
354   i->output->f = n;
355   return true;
356 }
357
358 /* Parses RBHEX format. */
359 static bool
360 parse_RBHEX (struct data_in *i)
361 {
362   double d;
363   size_t j;
364
365   memset (&d, 0, sizeof d);
366   for (j = 0; !ss_is_empty (i->input) && j < sizeof d; j++) 
367     {
368       int hi = ss_get_char (&i->input);
369       int lo = ss_get_char (&i->input);
370       if (lo == EOF)
371         {
372           data_warning (i, _("Field must have even length."));
373           return false;
374         }
375       else if (!c_isxdigit (hi) || !c_isxdigit (lo))
376         {
377           data_warning (i, _("Field must contain only hex digits."));
378           return false;
379         }
380       ((unsigned char *) &d)[j] = 16 * hexit_value (hi) + hexit_value (lo); 
381     }
382   
383   i->output->f = d;
384   
385   return true;
386 }
387
388 /* Digits for Z format. */
389 static const char z_digits[] = "0123456789{ABCDEFGHI}JKLMNOPQR";
390
391 /* Returns true if C is a Z format digit, false otherwise. */
392 static bool
393 is_z_digit (int c) 
394 {
395   return c > 0 && strchr (z_digits, c) != NULL;
396 }
397
398 /* Returns the (absolute value of the) value of C as a Z format
399    digit. */
400 static int
401 z_digit_value (int c)
402 {
403   assert (is_z_digit (c));
404   return (strchr (z_digits, c) - z_digits) % 10;
405 }
406
407 /* Returns true if Z format digit C represents a negative value,
408    false otherwise. */
409 static bool
410 is_negative_z_digit (int c) 
411 {
412   assert (is_z_digit (c));
413   return (strchr (z_digits, c) - z_digits) >= 20;
414 }
415
416 /* Parses Z format. */
417 static bool
418 parse_Z (struct data_in *i)
419 {
420   struct string tmp;
421
422   int save_errno;
423
424   bool got_dot = false;
425   bool got_final_digit = false;
426  
427   /* Trim spaces and check for missing value representation. */
428   if (trim_spaces_and_check_missing (i))
429     return true;
430
431   ds_init_empty (&tmp);
432   ds_extend (&tmp, 64);
433
434   ds_put_char (&tmp, '+');
435   while (!ss_is_empty (i->input))
436     {
437       int c = ss_get_char (&i->input);
438       if (c_isdigit (c) && !got_final_digit)
439         ds_put_char (&tmp, c);
440       else if (is_z_digit (c) && !got_final_digit) 
441         {
442           ds_put_char (&tmp, z_digit_value (c) + '0');
443           if (is_negative_z_digit (c))
444             ds_data (&tmp)[0] = '-';
445           got_final_digit = true;
446         }
447       else if (c == '.' && !got_dot) 
448         {
449           ds_put_char (&tmp, '.');
450           got_dot = true; 
451         }
452       else 
453         {
454           ds_destroy (&tmp);
455           return false; 
456         }
457     }
458
459   if (!ss_is_empty (i->input))
460     {
461       if (ds_length (&tmp) == 1)
462         data_warning (i, _("Field contents are not numeric."));
463       else
464         data_warning (i, _("Number followed by garbage."));
465       ds_destroy (&tmp);
466       return false;
467     }
468
469   /* Let strtod() do the conversion. */
470   save_errno = errno;
471   errno = 0;
472   i->output->f = strtod (ds_cstr (&tmp), NULL);
473   if (errno == ERANGE) 
474     {
475       if (fabs (i->output->f) > 1)
476         {
477           data_warning (i, _("Too-large number set to system-missing."));
478           i->output->f = SYSMIS;
479         }
480       else 
481         {
482           data_warning (i, _("Too-small number set to zero."));
483           i->output->f = 0.0; 
484         }
485     }
486   else 
487     {
488       errno = save_errno;
489       if (!got_dot)
490         apply_implied_decimals (i);
491     }
492
493   ds_destroy (&tmp);
494   return true;
495 }
496
497 /* Parses IB format. */
498 static bool
499 parse_IB (struct data_in *i)
500 {
501   size_t bytes;
502   uint64_t value;
503   uint64_t sign_bit;
504
505   bytes = MIN (8, ss_length (i->input));
506   value = integer_get (input_integer_format, ss_data (i->input), bytes);
507
508   sign_bit = UINT64_C(1) << (8 * bytes - 1);
509   if (!(value & sign_bit)) 
510     i->output->f = value;
511   else 
512     {
513       /* Sign-extend to full 64 bits. */
514       value -= sign_bit << 1; 
515       i->output->f = -(double) -value;       
516     }
517
518   apply_implied_decimals (i);
519
520   return true;
521 }
522
523 /* Parses PIB format. */
524 static bool
525 parse_PIB (struct data_in *i)
526 {
527   i->output->f = integer_get (input_integer_format, ss_data (i->input),
528                               MIN (8, ss_length (i->input)));
529   
530   apply_implied_decimals (i);
531
532   return true;
533 }
534
535 /* Consumes the first character of S.  Stores its high 4 bits in
536    HIGH_NIBBLE and its low 4 bits in LOW_NIBBLE. */
537 static void
538 get_nibbles (struct substring *s, int *high_nibble, int *low_nibble) 
539 {
540   int c = ss_get_char (s);
541   assert (c != EOF);
542   *high_nibble = (c >> 4) & 15;
543   *low_nibble = c & 15;
544 }
545
546 /* Parses P format. */
547 static bool
548 parse_P (struct data_in *i)
549 {
550   int high_nibble, low_nibble;
551   
552   i->output->f = 0.0;
553
554   while (ss_length (i->input) > 1)
555     {
556       get_nibbles (&i->input, &high_nibble, &low_nibble);
557       if (high_nibble > 9 || low_nibble > 9)
558         return false;
559       i->output->f = (100 * i->output->f) + (10 * high_nibble) + low_nibble;
560     }
561
562   get_nibbles (&i->input, &high_nibble, &low_nibble);
563   if (high_nibble > 9)
564     return false;
565   i->output->f = (10 * i->output->f) + high_nibble;
566   if (low_nibble < 10) 
567     i->output->f = (10 * i->output->f) + low_nibble;
568   else if (low_nibble == 0xb || low_nibble == 0xd)
569     i->output->f = -i->output->f;
570
571   apply_implied_decimals (i);
572
573   return true;
574 }
575
576 /* Parses PK format. */
577 static bool
578 parse_PK (struct data_in *i)
579 {
580   i->output->f = 0.0;
581   while (!ss_is_empty (i->input))
582     {
583       int high_nibble, low_nibble;
584
585       get_nibbles (&i->input, &high_nibble, &low_nibble);
586       if (high_nibble > 9 || low_nibble > 9)
587         {
588           i->output->f = SYSMIS;
589           return true;
590         }
591       i->output->f = (100 * i->output->f) + (10 * high_nibble) + low_nibble;
592     }
593
594   apply_implied_decimals (i);
595
596   return true;
597 }
598
599 /* Parses RB format. */
600 static bool
601 parse_RB (struct data_in *i)
602 {
603   size_t size = float_get_size (input_float_format);
604   if (ss_length (i->input) >= size)
605     float_convert (input_float_format, ss_data (i->input),
606                    FLOAT_NATIVE_DOUBLE, &i->output->f);
607   else
608     i->output->f = SYSMIS;
609
610   return true;
611 }
612
613 /* Parses A format. */
614 static bool
615 parse_A (struct data_in *i)
616 {
617   buf_copy_rpad (i->output->s, i->width,
618                  ss_data (i->input), ss_length (i->input));
619   return true;
620 }
621
622 /* Parses AHEX format. */
623 static bool
624 parse_AHEX (struct data_in *i)
625 {
626   size_t j;
627   
628   for (j = 0; ; j++) 
629     {
630       int hi = ss_get_char (&i->input);
631       int lo = ss_get_char (&i->input);
632       if (hi == EOF)
633         break;
634       else if (lo == EOF)
635         {
636           data_warning (i, _("Field must have even length."));
637           return false;
638         }
639
640       if (!c_isxdigit (hi) || !c_isxdigit (lo))
641         {
642           data_warning (i, _("Field must contain only hex digits."));
643           return false;
644         }
645       
646       if (j < i->width)
647         i->output->s[j] = hexit_value (hi) * 16 + hexit_value (lo);
648     }
649
650   memset (i->output->s + j, ' ', i->width - j);
651   
652   return true;
653 }
654 \f
655 /* Date & time format components. */
656
657 /* Sign of a time value. */
658 enum time_sign 
659   {
660     SIGN_NO_TIME,       /* No time yet encountered. */
661     SIGN_POSITIVE,      /* Positive time. */
662     SIGN_NEGATIVE       /* Negative time. */
663   };
664
665 /* Parses a signed decimal integer from at most the first
666    MAX_DIGITS characters in I, storing the result into *RESULT.
667    Returns true if successful, false if no integer was
668    present. */
669 static bool
670 parse_int (struct data_in *i, long *result, size_t max_digits)
671 {
672   struct substring head = ss_head (i->input, max_digits);
673   size_t n = ss_get_long (&head, result);
674   if (n) 
675     {
676       ss_advance (&i->input, n);
677       return true;
678     }
679   else 
680     {
681       data_warning (i, _("Syntax error in date field."));
682       return false;
683     }
684 }
685
686 /* Parses a date integer between 1 and 31 from I, storing it into
687    *DAY.
688    Returns true if successful, false if no date was present. */
689 static bool
690 parse_day (struct data_in *i, long *day)
691 {
692   if (!parse_int (i, day, SIZE_MAX))
693     return false;
694   if (*day >= 1 && *day <= 31)
695     return true;
696
697   data_warning (i, _("Day (%ld) must be between 1 and 31."), *day);
698   return false;
699 }
700
701 /* Parses an integer from the beginning of I.
702    Adds SECONDS_PER_UNIT times the absolute value of the integer
703    to *TIME.
704    If *TIME_SIGN is SIGN_NO_TIME, allows a sign to precede the
705    time and sets *TIME_SIGN.  Otherwise, does not allow a sign.
706    Returns true if successful, false if no integer was present. */
707 static bool
708 parse_time_units (struct data_in *i, double seconds_per_unit,
709                   enum time_sign *time_sign, double *time)
710
711 {
712   long units;
713
714   if (*time_sign == SIGN_NO_TIME) 
715     {
716       if (ss_match_char (&i->input, '-'))
717         *time_sign = SIGN_NEGATIVE;
718       else
719         {
720           ss_match_char (&i->input, '+');
721           *time_sign = SIGN_POSITIVE; 
722         }
723     }
724   if (!parse_int (i, &units, SIZE_MAX))
725     return false;
726   if (units < 0) 
727     {
728       data_warning (i, _("Syntax error in date field."));
729       return false;
730     }
731   *time += units * seconds_per_unit;
732   return true;
733 }
734
735 /* Parses a data delimiter from the beginning of I.
736    Returns true if successful, false if no delimiter was
737    present. */
738 static bool
739 parse_date_delimiter (struct data_in *i)
740 {
741   if (ss_ltrim (&i->input, ss_cstr ("-/.," CC_SPACES)))
742     return true;
743
744   data_warning (i, _("Delimiter expected between fields in date."));
745   return false;
746 }
747
748 /* Parses spaces at the beginning of I. */
749 static void
750 parse_spaces (struct data_in *i)
751 {
752   ss_ltrim (&i->input, ss_cstr (CC_SPACES));
753 }
754
755 static struct substring
756 parse_name_token (struct data_in *i) 
757 {
758   struct substring token;
759   ss_get_chars (&i->input, ss_span (i->input, ss_cstr (CC_LETTERS)), &token);
760   return token;
761 }
762
763 /* Reads a name from I and sets *OUTPUT to the value associated
764    with that name.  If ALLOW_SUFFIXES is true, then names that
765    begin with one of the names are accepted; otherwise, only
766    exact matches (except for case) are allowed.
767    Returns true if successful, false otherwise. */
768 static bool
769 match_name (struct substring token, const char **names, long *output) 
770 {
771   int i;
772
773   for (i = 1; *names != NULL; i++) 
774     if (ss_equals_case (ss_cstr (*names++), token))
775       {
776         *output = i;
777         return true;
778       }
779   
780   return false;
781 }
782
783 /* Parses a month name or number from the beginning of I,
784    storing the month (in range 1...12) into *MONTH.
785    Returns true if successful, false if no month was present. */
786 static bool
787 parse_month (struct data_in *i, long *month)
788 {
789   if (c_isdigit (ss_first (i->input)))
790     {
791       if (!parse_int (i, month, SIZE_MAX))
792         return false;
793       if (*month >= 1 && *month <= 12)
794         return true;
795     }
796   else 
797     {
798       static const char *english_names[] = 
799         {
800           "jan", "feb", "mar", "apr", "may", "jun",
801           "jul", "aug", "sep", "oct", "nov", "dec",
802           NULL,
803         };
804   
805       static const char *roman_names[] = 
806         {
807           "i", "ii", "iii", "iv", "v", "vi",
808           "vii", "viii", "ix", "x", "xi", "xii",
809           NULL,
810         };
811
812       struct substring token = parse_name_token (i);
813       if (match_name (ss_head (token, 3), english_names, month)
814           || match_name (ss_head (token, 4), roman_names, month))
815         return true;
816     }
817
818   data_warning (i, _("Unrecognized month format.  Months may be specified "
819                      "as Arabic or Roman numerals or as at least 3 letters "
820                      "of their English names."));
821   return false;
822 }
823
824 /* Parses a year of at most MAX_DIGITS from the beginning of I,
825    storing a "4-digit" year into *YEAR. */
826 static bool
827 parse_year (struct data_in *i, long *year, size_t max_digits)
828 {
829   if (!parse_int (i, year, max_digits))
830     return false;
831   
832   if (*year >= 0 && *year <= 99) 
833     {
834       int epoch = get_epoch ();
835       int epoch_century = ROUND_DOWN (epoch, 100);
836       int epoch_offset = epoch - epoch_century;
837       if (*year >= epoch_offset)
838         *year += epoch_century;
839       else
840         *year += epoch_century + 100; 
841     }
842   if (*year >= 1582 || *year <= 19999)
843     return true;
844
845   data_warning (i, _("Year (%ld) must be between 1582 and 19999."), *year);
846   return false;
847 }
848
849 /* Returns true if input in I has been exhausted,
850    false otherwise. */
851 static bool
852 parse_trailer (struct data_in *i)
853 {
854   if (ss_is_empty (i->input))
855     return true;
856   
857   data_warning (i, _("Trailing garbage \"%.*s\" following date."),
858               (int) ss_length (i->input), ss_data (i->input));
859   return false;
860 }
861
862 /* Parses a 3-digit Julian day-of-year value from I into *YDAY.
863    Returns true if successful, false on failure. */
864 static bool
865 parse_yday (struct data_in *i, long *yday)
866 {
867   struct substring num_s;
868   long num;
869
870   ss_get_chars (&i->input, 3, &num_s);
871   if (ss_span (num_s, ss_cstr (CC_DIGITS)) != 3)
872     {
873       data_warning (i, _("Julian day must have exactly three digits."));
874       return false;
875     }
876   else if (!ss_get_long (&num_s, &num) || num < 1 || num > 366)
877     {
878       data_warning (i, _("Julian day (%ld) must be between 1 and 366."), num);
879       return false;
880     }
881
882   *yday = num;
883   return true;
884 }
885
886 /* Parses a quarter-of-year integer between 1 and 4 from I.
887    Stores the corresponding month into *MONTH.
888    Returns true if successful, false if no quarter was present. */
889 static bool
890 parse_quarter (struct data_in *i, long int *month)
891 {
892   long quarter;
893   
894   if (!parse_int (i, &quarter, SIZE_MAX))
895     return false;
896   if (quarter >= 1 && quarter <= 4) 
897     {
898       *month = (quarter - 1) * 3 + 1;
899       return true; 
900     }
901
902   data_warning (i, _("Quarter (%ld) must be between 1 and 4."), quarter);
903   return false;
904 }
905
906 /* Parses a week-of-year integer between 1 and 53 from I,
907    Stores the corresponding year-of-day into *YDAY.
908    Returns true if successful, false if no week was present. */
909 static bool
910 parse_week (struct data_in *i, long int *yday)
911 {
912   long week;
913   
914   if (!parse_int (i, &week, SIZE_MAX))
915     return false;
916   if (week >= 1 && week <= 53) 
917     {
918       *yday = (week - 1) * 7 + 1;
919       return true; 
920     }
921
922   data_warning (i, _("Week (%ld) must be between 1 and 53."), week);
923   return false;
924 }
925
926 /* Parses a time delimiter from the beginning of I.
927    Returns true if successful, false if no delimiter was
928    present. */
929 static bool
930 parse_time_delimiter (struct data_in *i)
931 {
932   if (ss_ltrim (&i->input, ss_cstr (":" CC_SPACES)) > 0)
933     return true;
934   
935   data_warning (i, _("Delimiter expected between fields in time."));
936   return false;
937 }
938
939 /* Parses minutes and optional seconds from the beginning of I.
940    The time is converted into seconds, which are added to
941    *TIME. 
942    Returns true if successful, false if an error was found. */
943 static bool
944 parse_minute_second (struct data_in *i, double *time)
945 {
946   long minute;
947   char buf[64];
948   char *cp;
949
950   /* Parse minutes. */
951   if (!parse_int (i, &minute, SIZE_MAX))
952     return false;
953   if (minute < 0 || minute > 59) 
954     {
955       data_warning (i, _("Minute (%ld) must be between 0 and 59."), minute);
956       return false; 
957     }
958   *time += 60. * minute;
959
960   /* Check for seconds. */
961   if (ss_ltrim (&i->input, ss_cstr (":" CC_SPACES)) == 0
962       || !c_isdigit (ss_first (i->input)))
963    return true;
964
965   /* Parse seconds. */
966   cp = buf;
967   while (c_isdigit (ss_first (i->input)))
968     *cp++ = ss_get_char (&i->input);
969   if (ss_match_char (&i->input, fmt_decimal_char (FMT_F)))
970     *cp++ = '.';
971   while (c_isdigit (ss_first (i->input)))
972     *cp++ = ss_get_char (&i->input);
973   *cp = '\0';
974   
975   *time += strtod (buf, NULL);
976
977   return true;
978 }
979
980 /* Parses a weekday name from the beginning of I,
981    storing a value of 1=Sunday...7=Saturday into *WEEKDAY.
982    Returns true if successful, false if an error was found. */
983 static bool
984 parse_weekday (struct data_in *i, long *weekday)
985 {
986   static const char *weekday_names[] = 
987     {
988       "su", "mo", "tu", "we", "th", "fr", "sa",
989       NULL,
990     };
991
992   struct substring token = parse_name_token (i);
993   bool ok = match_name (ss_head (token, 2), weekday_names, weekday);
994   if (!ok)
995     data_warning (i, _("Unrecognized weekday name.  At least the first two "
996                        "letters of an English weekday name must be "
997                        "specified."));
998   return ok;
999 }
1000 \f
1001 /* Date & time formats. */
1002
1003 /* Helper function for passing to
1004    calendar_gregorian_to_offset. */
1005 static void
1006 calendar_error (void *i_, const char *format, ...) 
1007 {
1008   struct data_in *i = i_;
1009   va_list args;
1010
1011   va_start (args, format);
1012   vdata_warning (i, format, args);
1013   va_end (args);
1014 }
1015
1016 /* Parses WKDAY format. */
1017 static bool
1018 parse_WKDAY (struct data_in *i)
1019 {
1020   long weekday;
1021
1022   if (trim_spaces_and_check_missing (i))
1023     return true;
1024
1025   if (!parse_weekday (i, &weekday)
1026       || !parse_trailer (i))
1027     return false;
1028
1029   i->output->f = weekday;
1030   return true;
1031 }
1032
1033 /* Parses MONTH format. */
1034 static bool
1035 parse_MONTH (struct data_in *i)
1036 {
1037   long month;
1038
1039   if (trim_spaces_and_check_missing (i))
1040     return true;
1041
1042   if (!parse_month (i, &month)
1043       || !parse_trailer (i))
1044     return false;
1045
1046   i->output->f = month;
1047   return true;
1048 }
1049
1050 /* Parses DATE, ADATE, EDATE, JDATE, SDATE, QYR, MOYR, KWYR,
1051    DATETIME, TIME and DTIME formats. */
1052 static bool
1053 parse_date (struct data_in *i)
1054 {
1055   long int year = INT_MIN;
1056   long int month = 1;
1057   long int day = 1;
1058   long int yday = 1;
1059   double time = 0, date = 0;
1060   enum time_sign time_sign = SIGN_NO_TIME;
1061
1062   const char *template = fmt_date_template (i->format);
1063   size_t template_width = strlen (template);
1064
1065   if (trim_spaces_and_check_missing (i))
1066     return true;
1067
1068   while (*template != '\0')
1069     {
1070       unsigned char ch = *template;
1071       int count = 1;
1072       bool ok;
1073       
1074       while (template[count] == ch) 
1075         count++;
1076       template += count;
1077       
1078       ok = true;
1079       switch (ch)
1080         {
1081         case 'd':
1082           ok = count < 3 ? parse_day (i, &day) : parse_yday (i, &yday);
1083           break;
1084         case 'm':
1085           ok = parse_month (i, &month);
1086           break;
1087         case 'y': 
1088           {
1089             size_t max_digits;
1090             if (!c_isalpha (*template))
1091               max_digits = SIZE_MAX;
1092             else 
1093               {
1094                 if (ss_length (i->input) >= template_width + 2)
1095                   max_digits = 4;
1096                 else
1097                   max_digits = 2; 
1098               }
1099             ok = parse_year (i, &year, max_digits); 
1100           }
1101           break;
1102         case 'q':
1103           ok = parse_quarter (i, &month);
1104           break;
1105         case 'w':
1106           ok = parse_week (i, &yday);
1107           break;
1108         case 'D':
1109           ok = parse_time_units (i, 60. * 60. * 24., &time_sign, &time);
1110           break;
1111         case 'H':
1112           ok = parse_time_units (i, 60. * 60., &time_sign, &time);
1113           break;
1114         case 'M':
1115           ok = parse_minute_second (i, &time);
1116           break;
1117         case '-':
1118         case '/':
1119         case '.':
1120         case 'X':
1121           ok = parse_date_delimiter (i);
1122           break;
1123         case ':':
1124           ok = parse_time_delimiter (i);
1125         case ' ':
1126           parse_spaces (i);
1127           break;
1128         default:
1129           assert (count == 1);
1130           if (!ss_match_char (&i->input, c_toupper (ch))
1131               && !ss_match_char (&i->input, c_tolower (ch)))
1132             {
1133               data_warning (i, _("`%c' expected in date field."), ch);
1134               return false;
1135             }
1136           break;
1137         }
1138       if (!ok)
1139         return false;
1140     }
1141   if (!parse_trailer (i))
1142     return false;
1143
1144   if (year != INT_MIN) 
1145     {
1146       double ofs = calendar_gregorian_to_offset (year, month, day,
1147                                                  calendar_error, i);
1148       if (ofs == SYSMIS)
1149         return false;
1150       date = (yday - 1 + ofs) * 60. * 60. * 24.;
1151     }
1152   else
1153     date = 0.;
1154   i->output->f = date + (time_sign == SIGN_NEGATIVE ? -time : time);
1155
1156   return true;
1157 }
1158 \f
1159 /* Utility functions. */
1160
1161 /* Outputs FORMAT with the given ARGS as a warning for input
1162    I. */
1163 static void
1164 vdata_warning (const struct data_in *i, const char *format, va_list args)
1165 {
1166   struct msg m;
1167   struct string text;
1168
1169   ds_init_empty (&text);
1170   ds_put_char (&text, '(');
1171   if (i->first_column != 0) 
1172     {
1173       if (i->first_column == i->last_column)
1174         ds_put_format (&text, _("column %d"), i->first_column);
1175       else
1176         ds_put_format (&text, _("columns %d-%d"),
1177                        i->first_column, i->last_column);
1178       ds_put_cstr (&text, ", ");
1179     }
1180   ds_put_format (&text, _("%s field) "), fmt_name (i->format));
1181   ds_put_vformat (&text, format, args);
1182
1183   m.category = MSG_DATA;
1184   m.severity = MSG_WARNING;
1185   m.text = ds_cstr (&text);
1186
1187   msg_emit (&m);
1188 }
1189
1190 /* Outputs FORMAT with the given ARGS as a warning for input
1191    I. */
1192 static void
1193 data_warning (const struct data_in *i, const char *format, ...) 
1194 {
1195   va_list args;
1196
1197   va_start (args, format);
1198   vdata_warning (i, format, args);
1199   va_end (args);
1200 }
1201
1202 /* Apply implied decimal places to output. */
1203 static void
1204 apply_implied_decimals (struct data_in *i) 
1205 {
1206   if (i->implied_decimals > 0)
1207     i->output->f /= pow (10., i->implied_decimals);
1208 }
1209
1210 /* Sets the default result for I.
1211    For a numeric format, this is the value set on SET BLANKS
1212    (typically system-missing); for a string format, it is all
1213    spaces. */
1214 static void
1215 default_result (struct data_in *i)
1216 {
1217   if (fmt_is_string (i->format))
1218     memset (i->output->s, ' ', i->width);
1219   else
1220     i->output->f = get_blanks ();
1221 }
1222
1223 /* Trims leading and trailing spaces from I.
1224    If the result is empty, or a single period character, then
1225    sets the default result and returns true; otherwise, returns
1226    false. */
1227 static bool
1228 trim_spaces_and_check_missing (struct data_in *i) 
1229 {
1230   ss_trim (&i->input, ss_cstr (" "));
1231   if (ss_is_empty (i->input) || ss_equals (i->input, ss_cstr (".")))
1232     {
1233       default_result (i);
1234       return true;
1235     }
1236   return false;
1237 }
1238
1239 /* Returns the integer value of hex digit C. */
1240 static int
1241 hexit_value (int c)
1242 {
1243   const char s[] = "0123456789abcdef";
1244   const char *cp = strchr (s, c_tolower ((unsigned char) c));
1245
1246   assert (cp != NULL);
1247   return cp - s;
1248 }