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