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