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