Categorical value cache added
[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 ((unsigned char) i->s[0])) 
95     i->s++;
96
97   while (i->s < i->e && isspace ((unsigned char) 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 ((unsigned char) *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 ((unsigned char) *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 char *cp;
295
296   i->v->f = 0;
297   for (cp = i->s; cp < i->e; cp++)
298     {
299       if (!isdigit ((unsigned char) *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 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 ((unsigned char) *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 char *cp;
349     
350     for (cp = i->s; cp < i->e; cp++)
351       if (!isxdigit ((unsigned char) *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 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 (buf, &tail);
444     if (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 unsigned 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 = (const unsigned char *) i->s;
471 #else
472   memcpy (buf, i->s, i->e - i->s);
473   buf_reverse (buf, i->e - i->s);
474   p = (const unsigned char *) 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 + (unsigned char) 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 + (unsigned char) 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 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) & 15);
530       i->v->f = i->v->f * 10 + (*cp & 15);
531     }
532   i->v->f = i->v->f * 10 + ((*cp >> 4) & 15);
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 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) & 15);
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 (sizeof u.c, (size_t) (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   buf_copy_rpad (i->v->s, i->format.w, i->s, i->e - i->s);
579   return true;
580 }
581
582 static inline bool
583 parse_AHEX (struct data_in *i)
584 {
585   /* Validate input. */
586   trim_whitespace (i);
587   if ((i->e - i->s) % 2)
588     {
589       dls_error (i, _("Field must have even length."));
590       return false;
591     }
592
593   {
594     const char *cp;
595     
596     for (cp = i->s; cp < i->e; cp++)
597       if (!isxdigit ((unsigned char) *cp))
598         {
599           dls_error (i, _("Field must contain only hex digits."));
600           return false;
601         }
602   }
603   
604   {
605     int j;
606     
607     /* Parse input. */
608     for (j = 0; j < min (i->e - i->s, i->format.w); j += 2)
609       i->v->s[j / 2] = hexit_value (i->s[j]) * 16 + hexit_value (i->s[j + 1]);
610     memset (i->v->s + (i->e - i->s) / 2, ' ', (i->format.w - (i->e - i->s)) / 2);
611   }
612   
613   return true;
614 }
615 \f
616 /* Date & time format components. */
617
618 /* Advances *CP past any whitespace characters. */
619 static inline void
620 skip_whitespace (struct data_in *i)
621 {
622   while (isspace ((unsigned char) *i->s))
623     i->s++;
624 }
625
626 static inline bool
627 parse_leader (struct data_in *i)
628 {
629   skip_whitespace (i);
630   return true;
631 }
632
633 static inline bool
634 force_have_char (struct data_in *i)
635 {
636   if (have_char (i))
637     return true;
638
639   dls_error (i, _("Unexpected end of field."));
640   return false;
641 }
642
643 static bool
644 parse_int (struct data_in *i, long *result)
645 {
646   bool negative = false;
647   
648   if (!force_have_char (i))
649     return false;
650
651   if (*i->s == '+')
652     {
653       i->s++;
654       force_have_char (i);
655     }
656   else if (*i->s == '-')
657     {
658       negative = true;
659       i->s++;
660       force_have_char (i);
661     }
662   
663   if (!isdigit ((unsigned char) *i->s))
664     {
665       dls_error (i, _("Digit expected in field."));
666       return false;
667     }
668
669   *result = 0;
670   for (;;)
671     {
672       *result = *result * 10 + (*i->s++ - '0');
673       if (!have_char (i) || !isdigit ((unsigned char) *i->s))
674         break;
675     }
676
677   if (negative)
678     *result = -*result;
679   return true;
680 }
681
682 static bool
683 parse_day (struct data_in *i, long *day)
684 {
685   if (!parse_int (i, day))
686     return false;
687   if (*day >= 1 && *day <= 31)
688     return true;
689
690   dls_error (i, _("Day (%ld) must be between 1 and 31."), *day);
691   return false;
692 }
693
694 static bool
695 parse_day_count (struct data_in *i, long *day_count)
696 {
697   return parse_int (i, day_count);
698 }
699
700 static bool
701 parse_date_delimiter (struct data_in *i)
702 {
703   bool delim = false;
704
705   while (have_char (i)
706          && (*i->s == '-' || *i->s == '/' || isspace ((unsigned char) *i->s)
707              || *i->s == '.' || *i->s == ','))
708     {
709       delim = true;
710       i->s++;
711     }
712   if (delim)
713     return true;
714
715   dls_error (i, _("Delimiter expected between fields in date."));
716   return false;
717 }
718
719 /* Association between a name and a value. */
720 struct enum_name
721   {
722     const char *name;           /* Name. */
723     bool can_abbreviate;        /* True if name may be abbreviated. */
724     int value;                  /* Value associated with name. */
725   };
726
727 /* Reads a name from I and sets *OUTPUT to the value associated
728    with that name.  Returns true if successful, false otherwise. */
729 static bool
730 parse_enum (struct data_in *i, const char *what,
731             const struct enum_name *enum_names,
732             long *output) 
733 {
734   const char *name;
735   size_t length;
736   const struct enum_name *ep;
737
738   /* Consume alphabetic characters. */
739   name = i->s;
740   length = 0;
741   while (have_char (i) && isalpha ((unsigned char) *i->s)) 
742     {
743       length++;
744       i->s++; 
745     }
746   if (length == 0) 
747     {
748       dls_error (i, _("Parse error at `%c' expecting %s."), *i->s, what);
749       return false;
750     }
751
752   for (ep = enum_names; ep->name != NULL; ep++)
753     if ((ep->can_abbreviate
754          && lex_id_match_len (ep->name, strlen (ep->name), name, length))
755         || (!ep->can_abbreviate && length == strlen (ep->name)
756             && !buf_compare_case (name, ep->name, length)))
757       {
758         *output = ep->value;
759         return true;
760       }
761
762   dls_error (i, _("Unknown %s `%.*s'."), what, (int) length, name);
763   return false;
764 }
765
766 static bool
767 parse_month (struct data_in *i, long *month)
768 {
769   static const struct enum_name month_names[] = 
770     {
771       {"january", true, 1},
772       {"february", true, 2},
773       {"march", true, 3},
774       {"april", true, 4},
775       {"may", true, 5},
776       {"june", true, 6},
777       {"july", true, 7},
778       {"august", true, 8},
779       {"september", true, 9},
780       {"october", true, 10},
781       {"november", true, 11},
782       {"december", true, 12},
783
784       {"i", false, 1},
785       {"ii", false, 2},
786       {"iii", false, 3},
787       {"iv", false, 4},
788       {"iiii", false, 4},
789       {"v", false, 5},
790       {"vi", false, 6},
791       {"vii", false, 7},
792       {"viii", false, 8},
793       {"ix", false, 9},
794       {"viiii", false, 9},
795       {"x", false, 10},
796       {"xi", false, 11},
797       {"xii", false, 12},
798
799       {NULL, false, 0},
800     };
801
802   if (!force_have_char (i))
803     return false;
804   
805   if (isdigit ((unsigned char) *i->s))
806     {
807       if (!parse_int (i, month))
808         return false;
809       if (*month >= 1 && *month <= 12)
810         return true;
811       
812       dls_error (i, _("Month (%ld) must be between 1 and 12."), *month);
813       return false;
814     }
815   else 
816     return parse_enum (i, _("month"), month_names, month);
817 }
818
819 static bool
820 parse_year (struct data_in *i, long *year)
821 {
822   if (!parse_int (i, year))
823     return false;
824   
825   if (*year >= 0 && *year <= 199)
826     *year += 1900;
827   if (*year >= 1582 || *year <= 19999)
828     return true;
829
830   dls_error (i, _("Year (%ld) must be between 1582 and 19999."), *year);
831   return false;
832 }
833
834 static bool
835 parse_trailer (struct data_in *i)
836 {
837   skip_whitespace (i);
838   if (!have_char (i))
839     return true;
840   
841   dls_error (i, _("Trailing garbage \"%s\" following date."), i->s);
842   return false;
843 }
844
845 static bool
846 parse_julian (struct data_in *i, long *julian)
847 {
848   if (!parse_int (i, julian))
849     return false;
850    
851   {
852     int day = *julian % 1000;
853
854     if (day < 1 || day > 366)
855       {
856         dls_error (i, _("Julian day (%d) must be between 1 and 366."), day);
857         return false;
858       }
859   }
860   
861   {
862     int year = *julian / 1000;
863
864     if (year >= 0 && year <= 199)
865       *julian += 1900000L;
866     else if (year < 1582 || year > 19999)
867       {
868         dls_error (i, _("Year (%d) must be between 1582 and 19999."), year);
869         return false;
870       }
871   }
872
873   return true;
874 }
875
876 static bool
877 parse_quarter (struct data_in *i, long *quarter)
878 {
879   if (!parse_int (i, quarter))
880     return false;
881   if (*quarter >= 1 && *quarter <= 4)
882     return true;
883
884   dls_error (i, _("Quarter (%ld) must be between 1 and 4."), *quarter);
885   return false;
886 }
887
888 static bool
889 parse_q_delimiter (struct data_in *i)
890 {
891   skip_whitespace (i);
892   if (!have_char (i) || tolower ((unsigned char) *i->s) != 'q')
893     {
894       dls_error (i, _("`Q' expected between quarter and year."));
895       return false;
896     }
897   i->s++;
898   skip_whitespace (i);
899   return true;
900 }
901
902 static bool
903 parse_week (struct data_in *i, long *week)
904 {
905   if (!parse_int (i, week))
906     return false;
907   if (*week >= 1 && *week <= 53)
908     return true;
909
910   dls_error (i, _("Week (%ld) must be between 1 and 53."), *week);
911   return false;
912 }
913
914 static bool
915 parse_wk_delimiter (struct data_in *i)
916 {
917   skip_whitespace (i);
918   if (i->s + 1 >= i->e
919       || tolower ((unsigned char) i->s[0]) != 'w'
920       || tolower ((unsigned char) i->s[1]) != 'k')
921     {
922       dls_error (i, _("`WK' expected between week and year."));
923       return false;
924     }
925   i->s += 2;
926   skip_whitespace (i);
927   return true;
928 }
929
930 static bool
931 parse_time_delimiter (struct data_in *i)
932 {
933   bool delim = false;
934
935   while (have_char (i) && (*i->s == ':' || *i->s == '.'
936                            || isspace ((unsigned char) *i->s)))
937     {
938       delim = true;
939       i->s++;
940     }
941
942   if (delim)
943     return true;
944   
945   dls_error (i, _("Delimiter expected between fields in time."));
946   return false;
947 }
948
949 static bool
950 parse_hour (struct data_in *i, long *hour)
951 {
952   if (!parse_int (i, hour))
953     return false;
954   if (*hour >= 0)
955     return true;
956   
957   dls_error (i, _("Hour (%ld) must be positive."), *hour);
958   return false;
959 }
960
961 static bool
962 parse_minute (struct data_in *i, long *minute)
963 {
964   if (!parse_int (i, minute))
965     return false;
966   if (*minute >= 0 && *minute <= 59)
967     return true;
968   
969   dls_error (i, _("Minute (%ld) must be between 0 and 59."), *minute);
970   return false;
971 }
972
973 static bool
974 parse_opt_second (struct data_in *i, double *second)
975 {
976   bool delim = false;
977
978   char buf[64];
979   char *cp;
980
981   while (have_char (i)
982          && (*i->s == ':' || *i->s == '.' || isspace ((unsigned char) *i->s)))
983     {
984       delim = true;
985       i->s++;
986     }
987   
988   if (!delim || !isdigit ((unsigned char) *i->s))
989     {
990       *second = 0.0;
991       return true;
992     }
993
994   cp = buf;
995   while (have_char (i) && isdigit ((unsigned char) *i->s))
996     *cp++ = *i->s++;
997   if (have_char (i) && *i->s == '.')
998     *cp++ = *i->s++;
999   while (have_char (i) && isdigit ((unsigned char) *i->s))
1000     *cp++ = *i->s++;
1001   *cp = '\0';
1002   
1003   *second = strtod (buf, NULL);
1004
1005   return true;
1006 }
1007
1008 static bool
1009 parse_hour24 (struct data_in *i, long *hour24)
1010 {
1011   if (!parse_int (i, hour24))
1012     return false;
1013   if (*hour24 >= 0 && *hour24 <= 23)
1014     return true;
1015   
1016   dls_error (i, _("Hour (%ld) must be between 0 and 23."), *hour24);
1017   return false;
1018 }
1019
1020      
1021 static bool
1022 parse_weekday (struct data_in *i, long *weekday)
1023 {
1024   static const struct enum_name weekday_names[] = 
1025     {
1026       {"sunday", true, 1},
1027       {"su", true, 1},
1028       {"monday", true, 2},
1029       {"mo", true, 2},
1030       {"tuesday", true, 3},
1031       {"tu", true, 3},
1032       {"wednesday", true, 4},
1033       {"we", true, 4},
1034       {"thursday", true, 5},
1035       {"th", true, 5},
1036       {"friday", true, 6},
1037       {"fr", true, 6},
1038       {"saturday", true, 7},
1039       {"sa", true, 7},
1040       
1041       {NULL, false, 0},
1042     };
1043
1044   return parse_enum (i, _("weekday"), weekday_names, weekday);
1045 }
1046
1047 static bool
1048 parse_spaces (struct data_in *i)
1049 {
1050   skip_whitespace (i);
1051   return true;
1052 }
1053
1054 static bool
1055 parse_sign (struct data_in *i, int *sign)
1056 {
1057   if (!force_have_char (i))
1058     return false;
1059
1060   switch (*i->s)
1061     {
1062     case '-':
1063       i->s++;
1064       *sign = -1;
1065       break;
1066
1067     case '+':
1068       i->s++;
1069       /* fall through */
1070
1071     default:
1072       *sign = 1;
1073       break;
1074     }
1075
1076   return true;
1077 }
1078 \f
1079 /* Date & time formats. */
1080
1081 static void
1082 calendar_error (void *i_, const char *format, ...) 
1083 {
1084   struct data_in *i = i_;
1085   va_list args;
1086
1087   va_start (args, format);
1088   vdls_error (i, format, args);
1089   va_end (args);
1090 }
1091
1092 static bool
1093 ymd_to_ofs (struct data_in *i, int year, int month, int day, double *ofs) 
1094 {
1095   *ofs = calendar_gregorian_to_offset (year, month, day, calendar_error, i);
1096   return *ofs != SYSMIS;
1097 }
1098
1099 static bool
1100 ymd_to_date (struct data_in *i, int year, int month, int day, double *date) 
1101 {
1102   if (ymd_to_ofs (i, year, month, day, date)) 
1103     {
1104       *date *= 60. * 60. * 24.;
1105       return true; 
1106     }
1107   else
1108     return false;
1109 }
1110
1111 static bool
1112 parse_DATE (struct data_in *i)
1113 {
1114   long day, month, year;
1115
1116   return (parse_leader (i)
1117           && parse_day (i, &day)
1118           && parse_date_delimiter (i)
1119           && parse_month (i, &month)
1120           && parse_date_delimiter (i)
1121           && parse_year (i, &year)
1122           && parse_trailer (i)
1123           && ymd_to_date (i, year, month, day, &i->v->f));
1124 }
1125
1126 static bool
1127 parse_ADATE (struct data_in *i)
1128 {
1129   long month, day, year;
1130
1131   return (parse_leader (i)
1132           && parse_month (i, &month)
1133           && parse_date_delimiter (i)
1134           && parse_day (i, &day)
1135           && parse_date_delimiter (i)
1136           && parse_year (i, &year)
1137           && parse_trailer (i)
1138           && ymd_to_date (i, year, month, day, &i->v->f));
1139 }
1140
1141 static bool
1142 parse_EDATE (struct data_in *i)
1143 {
1144   long month, day, year;
1145
1146   return (parse_leader (i)
1147           && parse_day (i, &day)
1148           && parse_date_delimiter (i)
1149           && parse_month (i, &month)
1150           && parse_date_delimiter (i)
1151           && parse_year (i, &year)
1152           && parse_trailer (i)
1153           && ymd_to_date (i, year, month, day, &i->v->f));
1154 }
1155
1156 static bool
1157 parse_SDATE (struct data_in *i)
1158 {
1159   long month, day, year;
1160
1161   return (parse_leader (i)
1162           && parse_year (i, &year)
1163           && parse_date_delimiter (i)
1164           && parse_month (i, &month)
1165           && parse_date_delimiter (i)
1166           && parse_day (i, &day)
1167           && parse_trailer (i)
1168           && ymd_to_date (i, year, month, day, &i->v->f));
1169 }
1170
1171 static bool
1172 parse_JDATE (struct data_in *i)
1173 {
1174   long julian;
1175   double ofs;
1176   
1177   if (!parse_leader (i)
1178       || !parse_julian (i, &julian)
1179       || !parse_trailer (i)
1180       || !ymd_to_ofs (i, julian / 1000, 1, 1, &ofs))
1181     return false;
1182
1183   i->v->f = (ofs + julian % 1000 - 1) * 60. * 60. * 24.;
1184   return true;
1185 }
1186
1187 static bool
1188 parse_QYR (struct data_in *i)
1189 {
1190   long quarter, year;
1191
1192   return (parse_leader (i)
1193           && parse_quarter (i, &quarter)
1194           && parse_q_delimiter (i)
1195           && parse_year (i, &year)
1196           && parse_trailer (i)
1197           && ymd_to_date (i, year, (quarter - 1) * 3 + 1, 1, &i->v->f));
1198 }
1199
1200 static bool
1201 parse_MOYR (struct data_in *i)
1202 {
1203   long month, year;
1204
1205   return (parse_leader (i)
1206           && parse_month (i, &month)
1207           && parse_date_delimiter (i)
1208           && parse_year (i, &year)
1209           && parse_trailer (i)
1210           && ymd_to_date (i, year, month, 1, &i->v->f));
1211 }
1212
1213 static bool
1214 parse_WKYR (struct data_in *i)
1215 {
1216   long week, year;
1217   double ofs;
1218
1219   if (!parse_leader (i)
1220       || !parse_week (i, &week)
1221       || !parse_wk_delimiter (i)
1222       || !parse_year (i, &year)
1223       || !parse_trailer (i))
1224     return false;
1225
1226   if (year != 1582) 
1227     {
1228       if (!ymd_to_ofs (i, year, 1, 1, &ofs))
1229         return false;
1230     }
1231   else 
1232     {
1233       if (ymd_to_ofs (i, 1583, 1, 1, &ofs))
1234         return false;
1235       ofs -= 365;
1236     }
1237
1238   i->v->f = (ofs + (week - 1) * 7) * 60. * 60. * 24.;
1239   return true;
1240 }
1241
1242 static bool
1243 parse_TIME (struct data_in *i)
1244 {
1245   int sign;
1246   double second;
1247   long hour, minute;
1248
1249   if (!parse_leader (i)
1250       || !parse_sign (i, &sign)
1251       || !parse_spaces (i)
1252       || !parse_hour (i, &hour)
1253       || !parse_time_delimiter (i)
1254       || !parse_minute (i, &minute)
1255       || !parse_opt_second (i, &second))
1256     return false;
1257
1258   i->v->f = (hour * 60. * 60. + minute * 60. + second) * sign;
1259   return true;
1260 }
1261
1262 static bool
1263 parse_DTIME (struct data_in *i)
1264 {
1265   int sign;
1266   long day_count, hour;
1267   double second;
1268   long minute;
1269
1270   if (!parse_leader (i)
1271       || !parse_sign (i, &sign)
1272       || !parse_spaces (i)
1273       || !parse_day_count (i, &day_count)
1274       || !parse_time_delimiter (i)
1275       || !parse_hour (i, &hour)
1276       || !parse_time_delimiter (i)
1277       || !parse_minute (i, &minute)
1278       || !parse_opt_second (i, &second))
1279     return false;
1280
1281   i->v->f = (day_count * 60. * 60. * 24.
1282              + hour * 60. * 60.
1283              + minute * 60.
1284              + second) * sign;
1285   return true;
1286 }
1287
1288 static bool
1289 parse_DATETIME (struct data_in *i)
1290 {
1291   long day, month, year;
1292   long hour24;
1293   double second;
1294   long minute;
1295
1296   if (!parse_leader (i)
1297       || !parse_day (i, &day)
1298       || !parse_date_delimiter (i)
1299       || !parse_month (i, &month)
1300       || !parse_date_delimiter (i)
1301       || !parse_year (i, &year)
1302       || !parse_time_delimiter (i)
1303       || !parse_hour24 (i, &hour24)
1304       || !parse_time_delimiter (i)
1305       || !parse_minute (i, &minute)
1306       || !parse_opt_second (i, &second)
1307       || !ymd_to_date (i, year, month, day, &i->v->f))
1308     return false;
1309
1310   i->v->f += hour24 * 60. * 60. + minute * 60. + second;
1311   return true;
1312 }
1313
1314 static bool
1315 parse_WKDAY (struct data_in *i)
1316 {
1317   long weekday;
1318
1319   if (!parse_leader (i)
1320       || !parse_weekday (i, &weekday)
1321       || !parse_trailer (i))
1322     return false;
1323
1324   i->v->f = weekday;
1325   return true;
1326 }
1327
1328 static bool
1329 parse_MONTH (struct data_in *i)
1330 {
1331   long month;
1332
1333   if (!parse_leader (i)
1334       || !parse_month (i, &month)
1335       || !parse_trailer (i))
1336     return false;
1337
1338   i->v->f = month;
1339   return true;
1340 }
1341 \f
1342 /* Main dispatcher. */
1343
1344 static void
1345 default_result (struct data_in *i)
1346 {
1347   const struct fmt_desc *const fmt = &formats[i->format.type];
1348
1349   /* Default to SYSMIS or blanks. */
1350   if (fmt->cat & FCAT_STRING)
1351     memset (i->v->s, ' ', i->format.w);
1352   else
1353     i->v->f = get_blanks();
1354 }
1355
1356 bool
1357 data_in (struct data_in *i)
1358 {
1359   const struct fmt_desc *const fmt = &formats[i->format.type];
1360
1361   assert (check_input_specifier (&i->format, 0));
1362
1363   /* Check that we've got a string to work with. */
1364   if (i->e == i->s || i->format.w <= 0)
1365     {
1366       default_result (i);
1367       return true;
1368     }
1369
1370   i->f2 = i->f1 + (i->e - i->s) - 1;
1371
1372   /* Make sure that the string isn't too long. */
1373   if (i->format.w > fmt->Imax_w)
1374     {
1375       dls_error (i, _("Field too long (%d characters).  Truncated after "
1376                    "character %d."),
1377                  i->format.w, fmt->Imax_w);
1378       i->format.w = fmt->Imax_w;
1379     }
1380
1381   if (fmt->cat & FCAT_BLANKS_SYSMIS)
1382     {
1383       const char *cp;
1384
1385       cp = i->s;
1386       for (;;)
1387         {
1388           if (!isspace ((unsigned char) *cp))
1389             break;
1390
1391           if (++cp == i->e)
1392             {
1393               i->v->f = get_blanks();
1394               return true;
1395             }
1396         }
1397     }
1398   
1399   {
1400     static bool (*const handlers[FMT_NUMBER_OF_FORMATS])(struct data_in *) = 
1401       {
1402         parse_numeric, parse_N, parse_numeric, parse_numeric,
1403         parse_numeric, parse_numeric, parse_numeric,
1404         parse_Z, parse_A, parse_AHEX, parse_IB, parse_P, parse_PIB,
1405         parse_PIBHEX, parse_PK, parse_RB, parse_RBHEX,
1406         NULL, NULL, NULL, NULL, NULL,
1407         parse_DATE, parse_EDATE, parse_SDATE, parse_ADATE, parse_JDATE,
1408         parse_QYR, parse_MOYR, parse_WKYR,
1409         parse_DATETIME, parse_TIME, parse_DTIME,
1410         parse_WKDAY, parse_MONTH,
1411       };
1412
1413     bool (*handler)(struct data_in *);
1414     bool success;
1415
1416     handler = handlers[i->format.type];
1417     assert (handler != NULL);
1418
1419     success = handler (i);
1420     if (!success)
1421       default_result (i);
1422
1423     return success;
1424   }
1425 }
1426 \f
1427 /* Utility function. */
1428
1429 /* Sets DI->{s,e} appropriately given that LINE has length LEN and the
1430    field starts at one-based column FC and ends at one-based column
1431    LC, inclusive. */
1432 void
1433 data_in_finite_line (struct data_in *di, const char *line, size_t len,
1434                      int fc, int lc)
1435 {
1436   di->s = line + ((size_t) fc <= len ? fc - 1 : len);
1437   di->e = line + ((size_t) lc <= len ? lc : len);
1438 }