Rewrite expression code.
[pspp-builds.git] / src / data-in.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include "data-in.h"
22 #include "error.h"
23 #include <math.h>
24 #include <ctype.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include "bool.h"
30 #include "error.h"
31 #include "getline.h"
32 #include "calendar.h"
33 #include "lexer.h"
34 #include "magic.h"
35 #include "misc.h"
36 #include "settings.h"
37 #include "str.h"
38 #include "var.h"
39 \f
40 #include "debug-print.h"
41
42 \f
43 /* Specialized error routine. */
44
45 static void dls_error (const struct data_in *, const char *format, ...)
46      PRINTF_FORMAT (2, 3);
47
48 static void
49 vdls_error (const struct data_in *i, const char *format, va_list args)
50 {
51   struct error e;
52   struct string title;
53
54   if (i->flags & DI_IGNORE_ERROR)
55     return;
56
57   ds_init (&title, 64);
58   if (!getl_reading_script)
59     ds_puts (&title, _("data-file error: "));
60   if (i->f1 == i->f2)
61     ds_printf (&title, _("(column %d"), i->f1);
62   else
63     ds_printf (&title, _("(columns %d-%d"), i->f1, i->f2);
64   ds_printf (&title, _(", field type %s) "), fmt_to_string (&i->format));
65     
66   e.class = DE;
67   err_location (&e.where);
68   e.title = ds_c_str (&title);
69
70   err_vmsg (&e, format, args);
71
72   ds_destroy (&title);
73 }
74
75 static void
76 dls_error (const struct data_in *i, const char *format, ...) 
77 {
78   va_list args;
79
80   va_start (args, format);
81   vdls_error (i, format, args);
82   va_end (args);
83 }
84
85 /* Excludes leading and trailing whitespace from I by adjusting
86    pointers. */
87 static void
88 trim_whitespace (struct data_in *i)
89 {
90   while (i->s < i->e && isspace (i->s[0])) 
91     i->s++;
92
93   while (i->s < i->e && isspace (i->e[-1]))
94     i->e--;
95 }
96
97 /* Returns nonzero if we're not at the end of the string being
98    parsed. */
99 static inline int
100 have_char (struct data_in *i)
101 {
102   return i->s < i->e;
103 }
104 \f
105 /* Format parsers. */ 
106
107 static int parse_int (struct data_in *i, long *result);
108
109 /* This function is based on strtod() from the GNU C library. */
110 static int
111 parse_numeric (struct data_in *i)
112 {
113   short int sign;               /* +1 or -1. */
114   double num;                   /* The number so far.  */
115
116   int got_dot;                  /* Found a decimal point.  */
117   int got_digit;                /* Count of digits.  */
118
119   int decimal;                  /* Decimal point character. */
120   int grouping;                 /* Grouping character. */
121
122   long int exponent;            /* Number's exponent. */
123   int type;                     /* Usually same as i->format.type. */
124
125   trim_whitespace (i);
126
127   type = i->format.type;
128   if (type == FMT_DOLLAR && have_char (i) && *i->s == '$')
129     {
130       i->s++;
131       type = FMT_COMMA;
132     }
133
134   /* Get the sign.  */
135   if (have_char (i))
136     {
137       sign = *i->s == '-' ? -1 : 1;
138       if (*i->s == '-' || *i->s == '+')
139         i->s++;
140     }
141   else
142     sign = 1;
143   
144   if (type != FMT_DOT)
145     {
146       decimal = get_decimal();
147       grouping = get_grouping();
148     }
149   else
150     {
151       decimal = get_grouping();
152       grouping = get_decimal();
153     }
154
155   i->v->f = SYSMIS;
156   num = 0.0;
157   got_dot = 0;
158   got_digit = 0;
159   exponent = 0;
160   for (; have_char (i); i->s++)
161     {
162       if (isdigit (*i->s))
163         {
164           got_digit++;
165
166           /* Make sure that multiplication by 10 will not overflow.  */
167           if (num > DBL_MAX * 0.1)
168             /* The value of the digit doesn't matter, since we have already
169                gotten as many digits as can be represented in a `double'.
170                This doesn't necessarily mean the result will overflow.
171                The exponent may reduce it to within range.
172
173                We just need to record that there was another
174                digit so that we can multiply by 10 later.  */
175             ++exponent;
176           else
177             num = (num * 10.0) + (*i->s - '0');
178
179           /* Keep track of the number of digits after the decimal point.
180              If we just divided by 10 here, we would lose precision.  */
181           if (got_dot)
182             --exponent;
183         }
184       else if (!got_dot && *i->s == decimal)
185         /* Record that we have found the decimal point.  */
186         got_dot = 1;
187       else if ((type != FMT_COMMA && type != FMT_DOT) || *i->s != grouping)
188         /* Any other character terminates the number.  */
189         break;
190     }
191
192   if (!got_digit)
193     {
194       if (got_dot)
195         {
196           i->v->f = SYSMIS;
197           return 1;
198         }
199       goto noconv;
200     }
201   
202   if (have_char (i)
203       && (tolower (*i->s) == 'e' || tolower (*i->s) == 'd'
204           || (type == FMT_E && (*i->s == '+' || *i->s == '-'))))
205     {
206       /* Get the exponent specified after the `e' or `E'.  */
207       long exp;
208
209       if (isalpha (*i->s))
210         i->s++;
211       if (!parse_int (i, &exp))
212         goto noconv;
213
214       exponent += exp;
215     }
216   else if (!got_dot)
217     exponent -= i->format.d;
218
219   if (type == FMT_PCT && have_char (i) && *i->s == '%')
220     i->s++;
221   if (i->s < i->e)
222     {
223       dls_error (i, _("Field contents followed by garbage."));
224       i->v->f = SYSMIS;
225       return 0;
226     }
227
228   if (num == 0.0)
229     {
230       i->v->f = 0.0;
231       return 1;
232     }
233
234   /* Multiply NUM by 10 to the EXPONENT power, checking for overflow
235      and underflow.  */
236
237   if (exponent < 0)
238     {
239       if (-exponent + got_digit > -(DBL_MIN_10_EXP) + 5
240           || num < DBL_MIN * pow (10.0, (double) -exponent))
241         goto underflow;
242       num *= pow (10.0, (double) exponent);
243     }
244   else if (exponent > 0)
245     {
246       if (num > DBL_MAX * pow (10.0, (double) -exponent))
247         goto overflow;
248       num *= pow (10.0, (double) exponent);
249     }
250
251   i->v->f = sign * num;
252   return 1;
253
254 overflow:
255   /* Return an overflow error.  */
256   dls_error (i, _("Overflow in floating-point constant."));
257   i->v->f = SYSMIS;
258   return 0;
259
260 underflow:
261   /* Return an underflow error.  */
262   dls_error (i, _("Underflow in floating-point constant."));
263   i->v->f = 0.0;
264   return 0;
265
266 noconv:
267   /* There was no number.  */
268   dls_error (i, _("Field does not form a valid floating-point constant."));
269   i->v->f = SYSMIS;
270   return 0;
271 }
272
273 /* Returns the integer value of hex digit C. */
274 static inline int
275 hexit_value (int c)
276 {
277   const char s[] = "0123456789abcdef";
278   const char *cp = strchr (s, tolower ((unsigned char) c));
279
280   assert (cp != NULL);
281   return cp - s;
282 }
283
284 static inline int
285 parse_N (struct data_in *i)
286 {
287   const unsigned char *cp;
288
289   i->v->f = 0;
290   for (cp = i->s; cp < i->e; cp++)
291     {
292       if (!isdigit (*cp))
293         {
294           dls_error (i, _("All characters in field must be digits."));
295           return 0;
296         }
297
298       i->v->f = i->v->f * 10.0 + *cp - '0';
299     }
300
301   if (i->format.d)
302     i->v->f /= pow (10.0, i->format.d);
303   return 1;
304 }
305
306 static inline int
307 parse_PIBHEX (struct data_in *i)
308 {
309   double n;
310   const unsigned char *cp;
311
312   trim_whitespace (i);
313
314   n = 0.0;
315   for (cp = i->s; cp < i->e; cp++)
316     {
317       if (!isxdigit (*cp))
318         {
319           dls_error (i, _("Unrecognized character in field."));
320           return 0;
321         }
322
323       n = n * 16.0 + hexit_value (*cp);
324     }
325   
326   i->v->f = n;
327   return 1;
328 }
329
330 static inline int
331 parse_RBHEX (struct data_in *i)
332 {
333   /* Validate input. */
334   trim_whitespace (i);
335   if ((i->e - i->s) % 2)
336     {
337       dls_error (i, _("Field must have even length."));
338       return 0;
339     }
340   
341   {
342     const unsigned char *cp;
343     
344     for (cp = i->s; cp < i->e; cp++)
345       if (!isxdigit (*cp))
346         {
347           dls_error (i, _("Field must contain only hex digits."));
348           return 0;
349         }
350   }
351   
352   /* Parse input. */
353   {
354     union
355       {
356         double d;
357         unsigned char c[sizeof (double)];
358       }
359     u;
360
361     int j;
362
363     memset (u.c, 0, sizeof u.c);
364     for (j = 0; j < min ((i->e - i->s) / 2, sizeof u.d); j++)
365       u.c[j] = 16 * hexit_value (i->s[j * 2]) + hexit_value (i->s[j * 2 + 1]);
366
367     i->v->f = u.d;
368   }
369   
370   return 1;
371 }
372
373 static inline int
374 parse_Z (struct data_in *i)
375 {
376   char buf[64];
377
378   /* Warn user that we suck. */
379   {
380     static int warned;
381
382     if (!warned)
383       {
384         msg (MW, 
385              _("Quality of zoned decimal (Z) input format code is "
386                "suspect.  Check your results three times. Report bugs "
387                 "to %s."),PACKAGE_BUGREPORT);
388         warned = 1;
389       }
390   }
391
392   /* Validate input. */
393   trim_whitespace (i);
394
395   if (i->e - i->s < 2)
396     {
397       dls_error (i, _("Zoned decimal field contains fewer than 2 "
398                       "characters."));
399       return 0;
400     }
401
402   /* Copy sign into buf[0]. */
403   if ((i->e[-1] & 0xc0) != 0xc0)
404     {
405       dls_error (i, _("Bad sign byte in zoned decimal number."));
406       return 0;
407     }
408   buf[0] = (i->e[-1] ^ (i->e[-1] >> 1)) & 0x10 ? '-' : '+';
409
410   /* Copy digits into buf[1 ... len - 1] and terminate string. */
411   {
412     const unsigned char *sp;
413     char *dp;
414
415     for (sp = i->s, dp = buf + 1; sp < i->e - 1; sp++, dp++)
416       if (*sp == '.')
417         *dp = '.';
418       else if ((*sp & 0xf0) == 0xf0 && (*sp & 0xf) < 10)
419         *dp = (*sp & 0xf) + '0';
420       else
421         {
422           dls_error (i, _("Format error in zoned decimal number."));
423           return 0;
424         }
425
426     *dp = '\0';
427   }
428
429   /* Parse as number. */
430   {
431     char *tail;
432     
433     i->v->f = strtod ((char *) buf, (char **) &tail);
434     if ((unsigned char *) tail != i->e)
435       {
436         dls_error (i, _("Error in syntax of zoned decimal number."));
437         return 0;
438       }
439   }
440   
441   return 1;
442 }
443
444 static inline int
445 parse_IB (struct data_in *i)
446 {
447   char buf[64];
448   const char *p;
449
450   unsigned char xor;
451
452   /* We want the data to be in big-endian format.  If this is a
453      little-endian machine, reverse the byte order. */
454 #ifdef WORDS_BIGENDIAN
455   p = i->s;
456 #else
457   memcpy (buf, i->s, i->e - i->s);
458   mm_reverse (buf, i->e - i->s);
459   p = buf;
460 #endif
461
462   /* If the value is negative, we need to logical-NOT each value
463      before adding it. */
464   if (p[0] & 0x80)
465     xor = 0xff;
466   else
467     xor = 0x00;
468   
469   {
470     int j;
471
472     i->v->f = 0.0;
473     for (j = 0; j < i->e - i->s; j++)
474       i->v->f = i->v->f * 256.0 + (p[j] ^ xor);
475   }
476
477   /* If the value is negative, add 1 and set the sign, to complete a
478      two's-complement negation. */
479   if (p[0] & 0x80)
480     i->v->f = -(i->v->f + 1.0);
481
482   if (i->format.d)
483     i->v->f /= pow (10.0, i->format.d);
484
485   return 1;
486 }
487
488 static inline int
489 parse_PIB (struct data_in *i)
490 {
491   int j;
492
493   i->v->f = 0.0;
494 #if WORDS_BIGENDIAN
495   for (j = 0; j < i->e - i->s; j++)
496     i->v->f = i->v->f * 256.0 + i->s[j];
497 #else
498   for (j = i->e - i->s - 1; j >= 0; j--)
499     i->v->f = i->v->f * 256.0 + i->s[j];
500 #endif
501
502   if (i->format.d)
503     i->v->f /= pow (10.0, i->format.d);
504
505   return 1;
506 }
507
508 static inline int
509 parse_P (struct data_in *i)
510 {
511   const unsigned char *cp;
512
513   i->v->f = 0.0;
514   for (cp = i->s; cp < i->e - 1; cp++)
515     {
516       i->v->f = i->v->f * 10 + (*cp >> 4);
517       i->v->f = i->v->f * 10 + (*cp & 15);
518     }
519   i->v->f = i->v->f * 10 + (*cp >> 4);
520   if ((*cp ^ (*cp >> 1)) & 0x10)
521       i->v->f = -i->v->f;
522
523   if (i->format.d)
524     i->v->f /= pow (10.0, i->format.d);
525
526   return 1;
527 }
528
529 static inline int
530 parse_PK (struct data_in *i)
531 {
532   const unsigned char *cp;
533
534   i->v->f = 0.0;
535   for (cp = i->s; cp < i->e; cp++)
536     {
537       i->v->f = i->v->f * 10 + (*cp >> 4);
538       i->v->f = i->v->f * 10 + (*cp & 15);
539     }
540
541   if (i->format.d)
542     i->v->f /= pow (10.0, i->format.d);
543
544   return 1;
545 }
546
547 static inline int
548 parse_RB (struct data_in *i)
549 {
550   union
551     {
552       double d;
553       unsigned char c[sizeof (double)];
554     }
555   u;
556
557   memset (u.c, 0, sizeof u.c);
558   memcpy (u.c, i->s, min ((int) sizeof (u.c), i->e - i->s));
559   i->v->f = u.d;
560
561   return 1;
562 }
563
564 static inline int
565 parse_A (struct data_in *i)
566 {
567   ptrdiff_t len = i->e - i->s;
568   
569   if (len >= i->format.w)
570     memcpy (i->v->s, i->s, i->format.w);
571   else
572     {
573       memcpy (i->v->s, i->s, len);
574       memset (i->v->s + len, ' ', i->format.w - len);
575     }
576
577   return 1;
578 }
579
580 static inline int
581 parse_AHEX (struct data_in *i)
582 {
583   /* Validate input. */
584   trim_whitespace (i);
585   if ((i->e - i->s) % 2)
586     {
587       dls_error (i, _("Field must have even length."));
588       return 0;
589     }
590
591   {
592     const unsigned char *cp;
593     
594     for (cp = i->s; cp < i->e; cp++)
595       if (!isxdigit (*cp))
596         {
597           dls_error (i, _("Field must contain only hex digits."));
598           return 0;
599         }
600   }
601   
602   {
603     int j;
604     
605     /* Parse input. */
606     for (j = 0; j < min (i->e - i->s, i->format.w); j += 2)
607       i->v->s[j / 2] = hexit_value (i->s[j]) * 16 + hexit_value (i->s[j + 1]);
608     memset (i->v->s + (i->e - i->s) / 2, ' ', (i->format.w - (i->e - i->s)) / 2);
609   }
610   
611   return 1;
612 }
613 \f
614 /* Date & time format components. */
615
616 /* Advances *CP past any whitespace characters. */
617 static inline void
618 skip_whitespace (struct data_in *i)
619 {
620   while (isspace ((unsigned char) *i->s))
621     i->s++;
622 }
623
624 static inline int
625 parse_leader (struct data_in *i)
626 {
627   skip_whitespace (i);
628   return 1;
629 }
630
631 static inline int
632 force_have_char (struct data_in *i)
633 {
634   if (have_char (i))
635     return 1;
636
637   dls_error (i, _("Unexpected end of field."));
638   return 0;
639 }
640
641 static int
642 parse_int (struct data_in *i, long *result)
643 {
644   int negative = 0;
645   
646   if (!force_have_char (i))
647     return 0;
648
649   if (*i->s == '+')
650     {
651       i->s++;
652       force_have_char (i);
653     }
654   else if (*i->s == '-')
655     {
656       negative = 1;
657       i->s++;
658       force_have_char (i);
659     }
660   
661   if (!isdigit (*i->s))
662     {
663       dls_error (i, _("Digit expected in field."));
664       return 0;
665     }
666
667   *result = 0;
668   for (;;)
669     {
670       *result = *result * 10 + *i->s++ - '0';
671       if (!have_char (i) || !isdigit (*i->s))
672         break;
673     }
674
675   if (negative)
676     *result = -*result;
677   return 1;
678 }
679
680 static int
681 parse_day (struct data_in *i, long *day)
682 {
683   if (!parse_int (i, day))
684     return 0;
685   if (*day >= 1 && *day <= 31)
686     return 1;
687
688   dls_error (i, _("Day (%ld) must be between 1 and 31."), *day);
689   return 0;
690 }
691
692 static int
693 parse_day_count (struct data_in *i, long *day_count)
694 {
695   return parse_int (i, day_count);
696 }
697
698 static int
699 parse_date_delimiter (struct data_in *i)
700 {
701   int delim = 0;
702
703   while (have_char (i)
704          && (*i->s == '-' || *i->s == '/' || isspace (*i->s)
705              || *i->s == '.' || *i->s == ','))
706     {
707       delim = 1;
708       i->s++;
709     }
710   if (delim)
711     return 1;
712
713   dls_error (i, _("Delimiter expected between fields in date."));
714   return 0;
715 }
716
717 /* Formats NUMBER as Roman numerals in ROMAN, or as Arabic numerals if
718    the Roman expansion would be too long. */
719 static void
720 to_roman (int number, char roman[32])
721 {
722   int save_number = number;
723
724   struct roman_digit
725     {
726       int value;                /* Value corresponding to this digit. */
727       char name;                /* Digit name. */
728     };
729
730   static const struct roman_digit roman_tab[7] =
731   {
732     {1000, 'M'},
733     {500, 'D'},
734     {100, 'C'},
735     {50, 'L'},
736     {10, 'X'},
737     {5, 'V'},
738     {1, 'I'},
739   };
740
741   char *cp = roman;
742
743   int i, j;
744
745   assert (32 >= INT_DIGITS + 1);
746   if (number == 0)
747     goto arabic;
748
749   if (number < 0)
750     {
751       *cp++ = '-';
752       number = -number;
753     }
754
755   for (i = 0; i < 7; i++)
756     {
757       int digit = roman_tab[i].value;
758       while (number >= digit)
759         {
760           number -= digit;
761           if (cp > &roman[30])
762             goto arabic;
763           *cp++ = roman_tab[i].name;
764         }
765
766       for (j = i + 1; j < 7; j++)
767         {
768           if (i == 4 && j == 5) /* VX is not a shortened form of V. */
769             break;
770
771           digit = roman_tab[i].value - roman_tab[j].value;
772           while (number >= digit)
773             {
774               number -= digit;
775               if (cp > &roman[29])
776                 goto arabic;
777               *cp++ = roman_tab[j].name;
778               *cp++ = roman_tab[i].name;
779             }
780         }
781     }
782   *cp = 0;
783   return;
784
785 arabic:
786   sprintf (roman, "%d", save_number);
787 }
788
789 /* Returns true if C is a (lowercase) roman numeral. */
790 #define CHAR_IS_ROMAN(C)                                \
791         ((C) == 'x' || (C) == 'v' || (C) == 'i')
792
793 /* Returns the value of a single (lowercase) roman numeral. */
794 #define ROMAN_VALUE(C)                          \
795         ((C) == 'x' ? 10 : ((C) == 'v' ? 5 : 1))
796
797 static int
798 parse_month (struct data_in *i, long *month)
799 {
800   if (!force_have_char (i))
801     return 0;
802   
803   if (isdigit (*i->s))
804     {
805       if (!parse_int (i, month))
806         return 0;
807       if (*month >= 1 && *month <= 12)
808         return 1;
809       
810       dls_error (i, _("Month (%ld) must be between 1 and 12."), *month);
811       return 0;
812     }
813
814   if (CHAR_IS_ROMAN (tolower (*i->s)))
815     {
816       int last = ROMAN_VALUE (tolower (*i->s));
817
818       *month = 0;
819       for (;;)
820         {
821           int value;
822
823           i->s++;
824           if (!have_char || !CHAR_IS_ROMAN (tolower (*i->s)))
825             {
826               if (last != INT_MAX)
827                 *month += last;
828               break;
829             }
830
831           value = ROMAN_VALUE (tolower (*i->s));
832           if (last == INT_MAX)
833             *month += value;
834           else if (value > last)
835             {
836               *month += value - last;
837               last = INT_MAX;
838             }
839           else
840             {
841               *month += last;
842               last = value;
843             }
844         }
845
846       if (*month < 1 || *month > 12)
847         {
848           char buf[32];
849
850           to_roman (*month, buf);
851           dls_error (i, _("Month (%s) must be between I and XII."), buf);
852           return 0;
853         }
854       
855       return 1;
856     }
857   
858   {
859     static const char *months[12] =
860       {
861         "january", "february", "march", "april", "may", "june",
862         "july", "august", "september", "october", "november", "december",
863       };
864
865     char month_buf[32];
866     char *mp;
867
868     int j;
869
870     for (mp = month_buf;
871          have_char (i) && isalpha (*i->s) && mp < &month_buf[31];
872          i->s++)
873       *mp++ = tolower (*i->s);
874     *mp = '\0';
875
876     if (have_char (i) && isalpha (*i->s))
877       {
878         dls_error (i, _("Month name (%s...) is too long."), month_buf);
879         return 0;
880       }
881
882     for (j = 0; j < 12; j++)
883       if (lex_id_match (months[j], month_buf))
884         {
885           *month = j + 1;
886           return 1;
887         }
888
889     dls_error (i, _("Bad month name (%s)."), month_buf);
890     return 0;
891   }
892 }
893
894 static int
895 parse_year (struct data_in *i, long *year)
896 {
897   if (!parse_int (i, year))
898     return 0;
899   
900   if (*year >= 0 && *year <= 199)
901     *year += 1900;
902   if (*year >= 1582 || *year <= 19999)
903     return 1;
904
905   dls_error (i, _("Year (%ld) must be between 1582 and 19999."), *year);
906   return 0;
907 }
908
909 static int
910 parse_trailer (struct data_in *i)
911 {
912   skip_whitespace (i);
913   if (!have_char (i))
914     return 1;
915   
916   dls_error (i, _("Trailing garbage \"%s\" following date."), i->s);
917   return 0;
918 }
919
920 static int
921 parse_julian (struct data_in *i, long *julian)
922 {
923   if (!parse_int (i, julian))
924     return 0;
925    
926   {
927     int day = *julian % 1000;
928
929     if (day < 1 || day > 366)
930       {
931         dls_error (i, _("Julian day (%d) must be between 1 and 366."), day);
932         return 0;
933       }
934   }
935   
936   {
937     int year = *julian / 1000;
938
939     if (year >= 0 && year <= 199)
940       *julian += 1900000L;
941     else if (year < 1582 || year > 19999)
942       {
943         dls_error (i, _("Year (%d) must be between 1582 and 19999."), year);
944         return 0;
945       }
946   }
947
948   return 1;
949 }
950
951 static int
952 parse_quarter (struct data_in *i, long *quarter)
953 {
954   if (!parse_int (i, quarter))
955     return 0;
956   if (*quarter >= 1 && *quarter <= 4)
957     return 1;
958
959   dls_error (i, _("Quarter (%ld) must be between 1 and 4."), *quarter);
960   return 0;
961 }
962
963 static int
964 parse_q_delimiter (struct data_in *i)
965 {
966   skip_whitespace (i);
967   if (!have_char (i) || tolower (*i->s) != 'q')
968     {
969       dls_error (i, _("`Q' expected between quarter and year."));
970       return 0;
971     }
972   i->s++;
973   skip_whitespace (i);
974   return 1;
975 }
976
977 static int
978 parse_week (struct data_in *i, long *week)
979 {
980   if (!parse_int (i, week))
981     return 0;
982   if (*week >= 1 && *week <= 53)
983     return 1;
984
985   dls_error (i, _("Week (%ld) must be between 1 and 53."), *week);
986   return 0;
987 }
988
989 static int
990 parse_wk_delimiter (struct data_in *i)
991 {
992   skip_whitespace (i);
993   if (i->s + 1 >= i->e
994       || tolower (i->s[0]) != 'w' || tolower (i->s[1]) != 'k')
995     {
996       dls_error (i, _("`WK' expected between week and year."));
997       return 0;
998     }
999   i->s += 2;
1000   skip_whitespace (i);
1001   return 1;
1002 }
1003
1004 static int
1005 parse_time_delimiter (struct data_in *i)
1006 {
1007   int delim = 0;
1008
1009   while (have_char (i)
1010          && (*i->s == ':' || *i->s == '.' || isspace (*i->s)))
1011     {
1012       delim = 1;
1013       i->s++;
1014     }
1015
1016   if (delim)
1017     return 1;
1018   
1019   dls_error (i, _("Delimiter expected between fields in time."));
1020   return 0;
1021 }
1022
1023 static int
1024 parse_hour (struct data_in *i, long *hour)
1025 {
1026   if (!parse_int (i, hour))
1027     return 0;
1028   if (*hour >= 0)
1029     return 1;
1030   
1031   dls_error (i, _("Hour (%ld) must be positive."), *hour);
1032   return 0;
1033 }
1034
1035 static int
1036 parse_minute (struct data_in *i, long *minute)
1037 {
1038   if (!parse_int (i, minute))
1039     return 0;
1040   if (*minute >= 0 && *minute <= 59)
1041     return 1;
1042   
1043   dls_error (i, _("Minute (%ld) must be between 0 and 59."), *minute);
1044   return 0;
1045 }
1046
1047 static int
1048 parse_opt_second (struct data_in *i, double *second)
1049 {
1050   int delim = 0;
1051
1052   char buf[64];
1053   char *cp;
1054
1055   while (have_char (i)
1056          && (*i->s == ':' || *i->s == '.' || isspace (*i->s)))
1057     {
1058       delim = 1;
1059       i->s++;
1060     }
1061   
1062   if (!delim || !isdigit (*i->s))
1063     {
1064       *second = 0.0;
1065       return 1;
1066     }
1067
1068   cp = buf;
1069   while (have_char (i) && isdigit (*i->s))
1070     *cp++ = *i->s++;
1071   if (have_char (i) && *i->s == '.')
1072     *cp++ = *i->s++;
1073   while (have_char (i) && isdigit (*i->s))
1074     *cp++ = *i->s++;
1075   *cp = '\0';
1076   
1077   *second = strtod (buf, NULL);
1078
1079   return 1;
1080 }
1081
1082 static int
1083 parse_hour24 (struct data_in *i, long *hour24)
1084 {
1085   if (!parse_int (i, hour24))
1086     return 0;
1087   if (*hour24 >= 0 && *hour24 <= 23)
1088     return 1;
1089   
1090   dls_error (i, _("Hour (%ld) must be between 0 and 23."), *hour24);
1091   return 0;
1092 }
1093
1094      
1095 static int
1096 parse_weekday (struct data_in *i, int *weekday)
1097 {
1098   /* PORTME */
1099   #define TUPLE(A,B)                            \
1100           (((A) << 8) + (B))
1101
1102   if (i->s + 1 >= i->e)
1103     {
1104       dls_error (i, _("Day of the week expected in date value."));
1105       return 0;
1106     }
1107
1108   switch (TUPLE (tolower (i->s[0]), tolower (i->s[1])))
1109     {
1110     case TUPLE ('s', 'u'):
1111       *weekday = 1;
1112       break;
1113
1114     case TUPLE ('m', 'o'):
1115       *weekday = 2;
1116       break;
1117
1118     case TUPLE ('t', 'u'):
1119       *weekday = 3;
1120       break;
1121
1122     case TUPLE ('w', 'e'):
1123       *weekday = 4;
1124       break;
1125
1126     case TUPLE ('t', 'h'):
1127       *weekday = 5;
1128       break;
1129
1130     case TUPLE ('f', 'r'):
1131       *weekday = 6;
1132       break;
1133
1134     case TUPLE ('s', 'a'):
1135       *weekday = 7;
1136       break;
1137
1138     default:
1139       dls_error (i, _("Day of the week expected in date value."));
1140       return 0;
1141     }
1142
1143   while (have_char (i) && isalpha (*i->s))
1144     i->s++;
1145
1146   return 1;
1147
1148   #undef TUPLE
1149 }
1150
1151 static int
1152 parse_spaces (struct data_in *i)
1153 {
1154   skip_whitespace (i);
1155   return 1;
1156 }
1157
1158 static int
1159 parse_sign (struct data_in *i, int *sign)
1160 {
1161   if (!force_have_char (i))
1162     return 0;
1163
1164   switch (*i->s)
1165     {
1166     case '-':
1167       i->s++;
1168       *sign = -1;
1169       break;
1170
1171     case '+':
1172       i->s++;
1173       /* fall through */
1174
1175     default:
1176       *sign = 1;
1177       break;
1178     }
1179
1180   return 1;
1181 }
1182 \f
1183 /* Date & time formats. */
1184
1185 static void
1186 calendar_error (void *i_, const char *format, ...) 
1187 {
1188   struct data_in *i = i_;
1189   va_list args;
1190
1191   va_start (args, format);
1192   vdls_error (i, format, args);
1193   va_end (args);
1194 }
1195
1196 static bool
1197 ymd_to_ofs (struct data_in *i, int year, int month, int day, double *ofs) 
1198 {
1199   *ofs = calendar_gregorian_to_offset (year, month, day, calendar_error, i);
1200   return *ofs != SYSMIS;
1201 }
1202
1203 static bool
1204 ymd_to_date (struct data_in *i, int year, int month, int day, double *date) 
1205 {
1206   if (ymd_to_ofs (i, year, month, day, date)) 
1207     {
1208       *date *= 60. * 60. * 24.;
1209       return true; 
1210     }
1211   else
1212     return false;
1213 }
1214
1215 static int
1216 parse_DATE (struct data_in *i)
1217 {
1218   long day, month, year;
1219
1220   return (parse_leader (i)
1221           && parse_day (i, &day)
1222           && parse_date_delimiter (i)
1223           && parse_month (i, &month)
1224           && parse_date_delimiter (i)
1225           && parse_year (i, &year)
1226           && parse_trailer (i)
1227           && ymd_to_date (i, year, month, day, &i->v->f));
1228 }
1229
1230 static int
1231 parse_ADATE (struct data_in *i)
1232 {
1233   long month, day, year;
1234
1235   return (parse_leader (i)
1236           && parse_month (i, &month)
1237           && parse_date_delimiter (i)
1238           && parse_day (i, &day)
1239           && parse_date_delimiter (i)
1240           && parse_year (i, &year)
1241           && parse_trailer (i)
1242           && ymd_to_date (i, year, month, day, &i->v->f));
1243 }
1244
1245 static int
1246 parse_EDATE (struct data_in *i)
1247 {
1248   long month, day, year;
1249
1250   return (parse_leader (i)
1251           && parse_day (i, &day)
1252           && parse_date_delimiter (i)
1253           && parse_month (i, &month)
1254           && parse_date_delimiter (i)
1255           && parse_year (i, &year)
1256           && parse_trailer (i)
1257           && ymd_to_date (i, year, month, day, &i->v->f));
1258 }
1259
1260 static int
1261 parse_SDATE (struct data_in *i)
1262 {
1263   long month, day, year;
1264
1265   return (parse_leader (i)
1266           && parse_year (i, &year)
1267           && parse_date_delimiter (i)
1268           && parse_month (i, &month)
1269           && parse_date_delimiter (i)
1270           && parse_day (i, &day)
1271           && parse_trailer (i)
1272           && ymd_to_date (i, year, month, day, &i->v->f));
1273 }
1274
1275 static int
1276 parse_JDATE (struct data_in *i)
1277 {
1278   long julian;
1279   double ofs;
1280   
1281   if (!parse_leader (i)
1282       || !parse_julian (i, &julian)
1283       || !parse_trailer (i)
1284       || !ymd_to_ofs (i, julian / 1000, 1, 1, &ofs))
1285     return 0;
1286
1287   i->v->f = (ofs + julian % 1000 - 1) * 60. * 60. * 24.;
1288   return 1;
1289 }
1290
1291 static int
1292 parse_QYR (struct data_in *i)
1293 {
1294   long quarter, year;
1295
1296   return (parse_leader (i)
1297           && parse_quarter (i, &quarter)
1298           && parse_q_delimiter (i)
1299           && parse_year (i, &year)
1300           && parse_trailer (i)
1301           && ymd_to_date (i, year, (quarter - 1) * 3 + 1, 1, &i->v->f));
1302 }
1303
1304 static int
1305 parse_MOYR (struct data_in *i)
1306 {
1307   long month, year;
1308
1309   return (parse_leader (i)
1310           && parse_month (i, &month)
1311           && parse_date_delimiter (i)
1312           && parse_year (i, &year)
1313           && parse_trailer (i)
1314           && ymd_to_date (i, year, month, 1, &i->v->f));
1315 }
1316
1317 static int
1318 parse_WKYR (struct data_in *i)
1319 {
1320   long week, year;
1321   double ofs;
1322
1323   if (!parse_leader (i)
1324       || !parse_week (i, &week)
1325       || !parse_wk_delimiter (i)
1326       || !parse_year (i, &year)
1327       || !parse_trailer (i))
1328     return 0;
1329
1330   if (year != 1582) 
1331     {
1332       if (!ymd_to_ofs (i, year, 1, 1, &ofs))
1333         return 0;
1334     }
1335   else 
1336     {
1337       if (ymd_to_ofs (i, 1583, 1, 1, &ofs))
1338         return 0;
1339       ofs -= 365;
1340     }
1341
1342   i->v->f = (ofs + (week - 1) * 7) * 60. * 60. * 24.;
1343   return 1;
1344 }
1345
1346 static int
1347 parse_TIME (struct data_in *i)
1348 {
1349   int sign;
1350   double second;
1351   long hour, minute;
1352
1353   if (!parse_leader (i)
1354       || !parse_sign (i, &sign)
1355       || !parse_spaces (i)
1356       || !parse_hour (i, &hour)
1357       || !parse_time_delimiter (i)
1358       || !parse_minute (i, &minute)
1359       || !parse_opt_second (i, &second))
1360     return 0;
1361
1362   i->v->f = (hour * 60. * 60. + minute * 60. + second) * sign;
1363   return 1;
1364 }
1365
1366 static int
1367 parse_DTIME (struct data_in *i)
1368 {
1369   int sign;
1370   long day_count, hour;
1371   double second;
1372   long minute;
1373
1374   if (!parse_leader (i)
1375       || !parse_sign (i, &sign)
1376       || !parse_spaces (i)
1377       || !parse_day_count (i, &day_count)
1378       || !parse_time_delimiter (i)
1379       || !parse_hour (i, &hour)
1380       || !parse_time_delimiter (i)
1381       || !parse_minute (i, &minute)
1382       || !parse_opt_second (i, &second))
1383     return 0;
1384
1385   i->v->f = (day_count * 60. * 60. * 24.
1386              + hour * 60. * 60.
1387              + minute * 60.
1388              + second) * sign;
1389   return 1;
1390 }
1391
1392 static int
1393 parse_DATETIME (struct data_in *i)
1394 {
1395   long day, month, year;
1396   long hour24;
1397   double second;
1398   long minute;
1399
1400   if (!parse_leader (i)
1401       || !parse_day (i, &day)
1402       || !parse_date_delimiter (i)
1403       || !parse_month (i, &month)
1404       || !parse_date_delimiter (i)
1405       || !parse_year (i, &year)
1406       || !parse_time_delimiter (i)
1407       || !parse_hour24 (i, &hour24)
1408       || !parse_time_delimiter (i)
1409       || !parse_minute (i, &minute)
1410       || !parse_opt_second (i, &second)
1411       || !ymd_to_date (i, year, month, day, &i->v->f))
1412     return 0;
1413
1414   i->v->f += hour24 * 60. * 60. + minute * 60. + second;
1415   return 1;
1416 }
1417
1418 static int
1419 parse_WKDAY (struct data_in *i)
1420 {
1421   int weekday;
1422
1423   if (!parse_leader (i)
1424       || !parse_weekday (i, &weekday)
1425       || !parse_trailer (i))
1426     return 0;
1427
1428   i->v->f = weekday;
1429   return 1;
1430 }
1431
1432 static int
1433 parse_MONTH (struct data_in *i)
1434 {
1435   long month;
1436
1437   if (!parse_leader (i)
1438       || !parse_month (i, &month)
1439       || !parse_trailer (i))
1440     return 0;
1441
1442   i->v->f = month;
1443   return 1;
1444 }
1445 \f
1446 /* Main dispatcher. */
1447
1448 static void
1449 default_result (struct data_in *i)
1450 {
1451   const struct fmt_desc *const fmt = &formats[i->format.type];
1452
1453   /* Default to SYSMIS or blanks. */
1454   if (fmt->cat & FCAT_STRING)
1455     memset (i->v->s, ' ', i->format.w);
1456   else
1457     i->v->f = get_blanks();
1458 }
1459
1460 int
1461 data_in (struct data_in *i)
1462 {
1463   const struct fmt_desc *const fmt = &formats[i->format.type];
1464
1465   /* Check that we've got a string to work with. */
1466   if (i->e == i->s || i->format.w <= 0)
1467     {
1468       default_result (i);
1469       return 1;
1470     }
1471
1472   i->f2 = i->f1 + (i->e - i->s) - 1;
1473
1474   /* Make sure that the string isn't too long. */
1475   if (i->format.w > fmt->Imax_w)
1476     {
1477       dls_error (i, _("Field too long (%d characters).  Truncated after "
1478                    "character %d."),
1479                  i->format.w, fmt->Imax_w);
1480       i->format.w = fmt->Imax_w;
1481     }
1482
1483   if (fmt->cat & FCAT_BLANKS_SYSMIS)
1484     {
1485       const unsigned char *cp;
1486
1487       cp = i->s;
1488       for (;;)
1489         {
1490           if (!isspace (*cp))
1491             break;
1492
1493           if (++cp == i->e)
1494             {
1495               i->v->f = get_blanks();
1496               return 1;
1497             }
1498         }
1499     }
1500   
1501   {
1502     static int (*const handlers[FMT_NUMBER_OF_FORMATS])(struct data_in *) = 
1503       {
1504         parse_numeric, parse_N, parse_numeric, parse_numeric,
1505         parse_numeric, parse_numeric, parse_numeric,
1506         parse_Z, parse_A, parse_AHEX, parse_IB, parse_P, parse_PIB,
1507         parse_PIBHEX, parse_PK, parse_RB, parse_RBHEX,
1508         NULL, NULL, NULL, NULL, NULL,
1509         parse_DATE, parse_EDATE, parse_SDATE, parse_ADATE, parse_JDATE,
1510         parse_QYR, parse_MOYR, parse_WKYR,
1511         parse_DATETIME, parse_TIME, parse_DTIME,
1512         parse_WKDAY, parse_MONTH,
1513       };
1514
1515     int (*handler)(struct data_in *);
1516     int success;
1517
1518     handler = handlers[i->format.type];
1519     assert (handler != NULL);
1520
1521     success = handler (i);
1522     if (!success)
1523       default_result (i);
1524
1525     return success;
1526   }
1527 }
1528 \f
1529 /* Utility function. */
1530
1531 /* Sets DI->{s,e} appropriately given that LINE has length LEN and the
1532    field starts at one-based column FC and ends at one-based column
1533    LC, inclusive. */
1534 void
1535 data_in_finite_line (struct data_in *di, const char *line, size_t len,
1536                      int fc, int lc)
1537 {
1538   di->s = line + ((size_t) fc <= len ? fc - 1 : len);
1539   di->e = line + ((size_t) lc <= len ? lc : len);
1540 }