Rewrite formatted data input routines to conform to SPSS data formats
[pspp-builds.git] / src / language / xforms / recode.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
22 #include <ctype.h>
23 #include <math.h>
24 #include <stdlib.h>
25
26 #include <data/case.h>
27 #include <data/data-in.h>
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/transformations.h>
31 #include <data/variable.h>
32 #include <language/command.h>
33 #include <language/lexer/lexer.h>
34 #include <language/lexer/variable-parser.h>
35 #include <language/lexer/range-parser.h>
36 #include <libpspp/alloc.h>
37 #include <libpspp/assertion.h>
38 #include <libpspp/compiler.h>
39 #include <libpspp/magic.h>
40 #include <libpspp/message.h>
41 #include <libpspp/message.h>
42 #include <libpspp/pool.h>
43 #include <libpspp/str.h>
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47 \f
48 /* Definitions. */
49
50 /* Type of source value for RECODE. */
51 enum map_in_type
52   {
53     MAP_SINGLE,                 /* Specific value. */
54     MAP_RANGE,                  /* Range of values. */
55     MAP_SYSMIS,                 /* System missing value. */
56     MAP_MISSING,                /* Any missing value. */
57     MAP_ELSE,                   /* Any value. */
58     MAP_CONVERT                 /* "123" => 123. */
59   };
60
61 /* A value involved in a RECODE mapping. */
62 union recode_value 
63   {
64     double f;                   /* Numeric. */
65     char *c;                    /* Short or long string. */
66   };
67
68 /* Describes input values to be mapped. */
69 struct map_in
70   {
71     enum map_in_type type;      /* One of MAP_*. */
72     union recode_value x, y;    /* Source values. */
73   };
74
75 /* Describes the value used as output from a mapping. */
76 struct map_out 
77   {
78     bool copy_input;            /* If true, copy input to output. */
79     union recode_value value;   /* If copy_input false, recoded value. */
80     int width;                  /* If copy_input false, output value width. */ 
81   };
82
83 /* Describes how to recode a single value or range of values into a
84    single value.  */
85 struct mapping 
86   {
87     struct map_in in;           /* Input values. */
88     struct map_out out;         /* Output value. */
89   };
90
91 /* RECODE transformation. */
92 struct recode_trns
93   {
94     struct pool *pool;
95
96     /* Variable types, for convenience. */
97     enum var_type src_type;     /* src_vars[*]->type. */
98     enum var_type dst_type;     /* dst_vars[*]->type. */
99
100     /* Variables. */
101     struct variable **src_vars; /* Source variables. */
102     struct variable **dst_vars; /* Destination variables. */
103     char **dst_names;           /* Name of dest variables, if they're new. */
104     size_t var_cnt;             /* Number of variables. */
105
106     /* Mappings. */
107     struct mapping *mappings;   /* Value mappings. */
108     size_t map_cnt;             /* Number of mappings. */
109   };
110
111 static bool parse_src_vars (struct lexer *, struct recode_trns *, const struct dictionary *dict);
112 static bool parse_mappings (struct lexer *, struct recode_trns *);
113 static bool parse_dst_vars (struct lexer *, struct recode_trns *, const struct dictionary *dict);
114
115 static void add_mapping (struct recode_trns *,
116                          size_t *map_allocated, const struct map_in *);
117
118 static bool parse_map_in (struct lexer *lexer, struct map_in *, struct pool *,
119                           enum var_type src_type, size_t max_src_width);
120 static void set_map_in_generic (struct map_in *, enum map_in_type);
121 static void set_map_in_num (struct map_in *, enum map_in_type, double, double);
122 static void set_map_in_str (struct map_in *, struct pool *,
123                             const struct string *, size_t width);
124
125 static bool parse_map_out (struct lexer *lexer, struct pool *, struct map_out *);
126 static void set_map_out_num (struct map_out *, double);
127 static void set_map_out_str (struct map_out *, struct pool *,
128                              const struct string *);
129
130 static void enlarge_dst_widths (struct recode_trns *);
131 static void create_dst_vars (struct recode_trns *, struct dictionary *);
132
133 static trns_proc_func recode_trns_proc;
134 static trns_free_func recode_trns_free;
135 \f
136 /* Parser. */
137
138 /* Parses the RECODE transformation. */
139 int
140 cmd_recode (struct lexer *lexer, struct dataset *ds)
141 {
142   do
143     {
144       struct recode_trns *trns
145         = pool_create_container (struct recode_trns, pool);
146
147       /* Parse source variable names,
148          then input to output mappings,
149          then destintation variable names. */
150       if (!parse_src_vars (lexer, trns, dataset_dict (ds) )
151           || !parse_mappings (lexer, trns)
152           || !parse_dst_vars (lexer, trns, dataset_dict (ds)))
153         {
154           recode_trns_free (trns);
155           return CMD_FAILURE;
156         }
157
158       /* Ensure that all the output strings are at least as wide
159          as the widest destination variable. */
160       if (trns->dst_type == ALPHA)
161         enlarge_dst_widths (trns);
162
163       /* Create destination variables, if needed.
164          This must be the final step; otherwise we'd have to
165          delete destination variables on failure. */
166       if (trns->src_vars != trns->dst_vars)
167         create_dst_vars (trns, dataset_dict (ds));
168
169       /* Done. */
170       add_transformation (ds, 
171                           recode_trns_proc, recode_trns_free, trns);
172     }
173   while (lex_match (lexer, '/'));
174   
175   return lex_end_of_command (lexer);
176 }
177
178 /* Parses a set of variables to recode into TRNS->src_vars and
179    TRNS->var_cnt.  Sets TRNS->src_type.  Returns true if
180    successful, false on parse error. */
181 static bool
182 parse_src_vars (struct lexer *lexer, 
183                 struct recode_trns *trns, const struct dictionary *dict) 
184 {
185   if (!parse_variables (lexer, dict, &trns->src_vars, &trns->var_cnt,
186                         PV_SAME_TYPE))
187     return false;
188   pool_register (trns->pool, free, trns->src_vars);
189   trns->src_type = trns->src_vars[0]->type;
190   return true;
191 }
192
193 /* Parses a set of mappings, which take the form (input=output),
194    into TRNS->mappings and TRNS->map_cnt.  Sets TRNS->dst_type.
195    Returns true if successful, false on parse error. */
196 static bool
197 parse_mappings (struct lexer *lexer, struct recode_trns *trns) 
198 {
199   size_t max_src_width;
200   size_t map_allocated;
201   bool have_dst_type;
202   size_t i;
203   
204   /* Find length of longest source variable. */
205   max_src_width = trns->src_vars[0]->width;
206   for (i = 1; i < trns->var_cnt; i++) 
207     {
208       size_t var_width = trns->src_vars[i]->width;
209       if (var_width > max_src_width)
210         max_src_width = var_width;
211     }
212       
213   /* Parse the mappings in parentheses. */
214   trns->mappings = NULL;
215   trns->map_cnt = 0;
216   map_allocated = 0;
217   have_dst_type = false;
218   if (!lex_force_match (lexer, '('))
219     return false;
220   do
221     {
222       enum var_type dst_type;
223
224       if (!lex_match_id (lexer, "CONVERT")) 
225         {
226           struct map_out out;
227           size_t first_map_idx;
228           size_t i;
229
230           first_map_idx = trns->map_cnt;
231
232           /* Parse source specifications. */
233           do
234             {
235               struct map_in in;
236               if (!parse_map_in (lexer, &in, trns->pool,
237                                  trns->src_type, max_src_width))
238                 return false;
239               add_mapping (trns, &map_allocated, &in);
240               lex_match (lexer, ',');
241             }
242           while (!lex_match (lexer, '='));
243
244           if (!parse_map_out (lexer, trns->pool, &out))
245             return false;
246           dst_type = out.width == 0 ? NUMERIC : ALPHA;
247           if (have_dst_type && dst_type != trns->dst_type)
248             {
249               msg (SE, _("Inconsistent target variable types.  "
250                          "Target variables "
251                          "must be all numeric or all string."));
252               return false;
253             }
254               
255           for (i = first_map_idx; i < trns->map_cnt; i++)
256             trns->mappings[i].out = out;
257         }
258       else 
259         {
260           /* Parse CONVERT as a special case. */
261           struct map_in in;
262           set_map_in_generic (&in, MAP_CONVERT);
263           add_mapping (trns, &map_allocated, &in);
264               
265           dst_type = NUMERIC;
266           if (trns->src_type != ALPHA
267               || (have_dst_type && trns->dst_type != NUMERIC)) 
268             {
269               msg (SE, _("CONVERT requires string input values and "
270                          "numeric output values."));
271               return false;
272             }
273         }
274       trns->dst_type = dst_type;
275       have_dst_type = true;
276
277       if (!lex_force_match (lexer, ')'))
278         return false; 
279     }
280   while (lex_match (lexer, '('));
281
282   return true;
283 }
284
285 /* Parses a mapping input value into IN, allocating memory from
286    POOL.  The source value type must be provided as SRC_TYPE and,
287    if string, the maximum width of a string source variable must
288    be provided in MAX_SRC_WIDTH.  Returns true if successful,
289    false on parse error. */
290 static bool
291 parse_map_in (struct lexer *lexer, struct map_in *in, struct pool *pool,
292               enum var_type src_type, size_t max_src_width)
293 {
294   if (lex_match_id (lexer, "ELSE"))
295     set_map_in_generic (in, MAP_ELSE);
296   else if (src_type == NUMERIC)
297     {
298       if (lex_match_id (lexer, "MISSING"))
299         set_map_in_generic (in, MAP_MISSING);
300       else if (lex_match_id (lexer, "SYSMIS"))
301         set_map_in_generic (in, MAP_SYSMIS);
302       else 
303         {
304           double x, y;
305           if (!parse_num_range (lexer, &x, &y, NULL))
306             return false;
307           set_map_in_num (in, x == y ? MAP_SINGLE : MAP_RANGE, x, y);
308         }
309     }
310   else
311     {
312       if (!lex_force_string (lexer))
313         return false;
314       set_map_in_str (in, pool, lex_tokstr (lexer), max_src_width);
315       lex_get (lexer);
316     }
317
318   return true;
319 }
320
321 /* Adds IN to the list of mappings in TRNS.
322    MAP_ALLOCATED is the current number of allocated mappings,
323    which is updated as needed. */
324 static void
325 add_mapping (struct recode_trns *trns,
326              size_t *map_allocated, const struct map_in *in)
327 {
328   struct mapping *m;
329   if (trns->map_cnt >= *map_allocated)
330     trns->mappings = pool_2nrealloc (trns->pool, trns->mappings,
331                                      map_allocated,
332                                      sizeof *trns->mappings);
333   m = &trns->mappings[trns->map_cnt++];
334   m->in = *in;
335 }
336
337 /* Sets IN as a mapping of the given TYPE. */
338 static void
339 set_map_in_generic (struct map_in *in, enum map_in_type type) 
340 {
341   in->type = type;
342 }
343
344 /* Sets IN as a numeric mapping of the given TYPE,
345    with X and Y as the two numeric values. */
346 static void
347 set_map_in_num (struct map_in *in, enum map_in_type type, double x, double y) 
348 {
349   in->type = type;
350   in->x.f = x;
351   in->y.f = y;
352 }
353
354 /* Sets IN as a string mapping, with STRING as the string,
355    allocated from POOL.  The string is padded with spaces on the
356    right to WIDTH characters long. */
357 static void
358 set_map_in_str (struct map_in *in, struct pool *pool,
359                 const struct string *string, size_t width) 
360 {
361   in->type = MAP_SINGLE;
362   in->x.c = pool_alloc_unaligned (pool, width);
363   buf_copy_rpad (in->x.c, width, ds_data (string), ds_length (string));
364 }
365
366 /* Parses a mapping output value into OUT, allocating memory from
367    POOL.  Returns true if successful, false on parse error. */
368 static bool
369 parse_map_out (struct lexer *lexer, struct pool *pool, struct map_out *out)
370 {
371   if (lex_is_number (lexer))
372     {
373       set_map_out_num (out, lex_number (lexer));
374       lex_get (lexer);
375     }
376   else if (lex_match_id (lexer, "SYSMIS"))
377     set_map_out_num (out, SYSMIS);
378   else if (lex_token (lexer) == T_STRING)
379     {
380       set_map_out_str (out, pool, lex_tokstr (lexer));
381       lex_get (lexer);
382     }
383   else if (lex_match_id (lexer, "COPY"))
384     out->copy_input = true;
385   else 
386     {
387       lex_error (lexer, _("expecting output value"));
388       return false;
389     }
390   return true; 
391 }
392
393 /* Sets OUT as a numeric mapping output with the given VALUE. */
394 static void
395 set_map_out_num (struct map_out *out, double value) 
396 {
397   out->copy_input = false;
398   out->value.f = value;
399   out->width = 0;
400 }
401
402 /* Sets OUT as a string mapping output with the given VALUE. */
403 static void
404 set_map_out_str (struct map_out *out, struct pool *pool,
405                  const struct string *value)
406 {
407   const char *string = ds_data (value);
408   size_t length = ds_length (value);
409
410   out->copy_input = false;
411   out->value.c = pool_alloc_unaligned (pool, length);
412   memcpy (out->value.c, string, length);
413   out->width = length;
414 }
415
416 /* Parses a set of target variables into TRNS->dst_vars and
417    TRNS->dst_names. */
418 static bool
419 parse_dst_vars (struct lexer *lexer, struct recode_trns *trns, 
420                 const struct dictionary *dict) 
421 {
422   size_t i;
423   
424   if (lex_match_id (lexer, "INTO"))
425     {
426       size_t name_cnt;
427       size_t i;
428
429       if (!parse_mixed_vars_pool (lexer, dict, trns->pool, 
430                                   &trns->dst_names, &name_cnt,
431                                   PV_NONE))
432         return false;
433
434       if (name_cnt != trns->var_cnt)
435         {
436           msg (SE, _("%u variable(s) cannot be recoded into "
437                      "%u variable(s).  Specify the same number "
438                      "of variables as source and target variables."),
439                (unsigned) trns->var_cnt, (unsigned) name_cnt);
440           return false;
441         }
442
443       trns->dst_vars = pool_nalloc (trns->pool,
444                                     trns->var_cnt, sizeof *trns->dst_vars);
445       for (i = 0; i < trns->var_cnt; i++)
446         {
447           struct variable *v;
448           v = trns->dst_vars[i] = dict_lookup_var (dict, trns->dst_names[i]);
449           if (v == NULL && trns->dst_type == ALPHA) 
450             {
451               msg (SE, _("There is no variable named "
452                          "%s.  (All string variables specified "
453                          "on INTO must already exist.  Use the "
454                          "STRING command to create a string "
455                          "variable.)"),
456                    trns->dst_names[i]);
457               return false;
458             }
459         }
460     }
461   else 
462     {
463       trns->dst_vars = trns->src_vars;
464       if (trns->src_type != trns->dst_type)
465         {
466           msg (SE, _("INTO is required with %s input values "
467                      "and %s output values."),
468                var_type_adj (trns->src_type),
469                var_type_adj (trns->dst_type));
470           return false;
471         }
472     }
473
474   for (i = 0; i < trns->var_cnt; i++)
475     {
476       struct variable *v = trns->dst_vars[i];
477       if (v != NULL && v->type != trns->dst_type)
478         {
479           msg (SE, _("Type mismatch.  Cannot store %s data in "
480                      "%s variable %s."),
481                trns->dst_type == ALPHA ? _("string") : _("numeric"),
482                v->type == ALPHA ? _("string") : _("numeric"),
483                v->name);
484           return false;
485         }
486     }
487
488   return true;
489 }
490
491 /* Ensures that all the output values in TRNS are as wide as the
492    widest destination variable. */
493 static void
494 enlarge_dst_widths (struct recode_trns *trns) 
495 {
496   size_t max_dst_width;
497   size_t i;
498
499   max_dst_width = 0;
500   for (i = 0; i < trns->var_cnt; i++)
501     {
502       struct variable *v = trns->dst_vars[i];
503       if (v->width > max_dst_width)
504         max_dst_width = v->width;
505     }
506
507   for (i = 0; i < trns->map_cnt; i++)
508     {
509       struct map_out *out = &trns->mappings[i].out;
510       if (!out->copy_input && out->width < max_dst_width) 
511         {
512           char *s = pool_alloc_unaligned (trns->pool, max_dst_width + 1);
513           str_copy_rpad (s, max_dst_width + 1, out->value.c);
514           out->value.c = s;
515         }
516     }
517 }
518
519 /* Creates destination variables that don't already exist. */
520 static void
521 create_dst_vars (struct recode_trns *trns, struct dictionary *dict)
522 {
523   size_t i;
524
525   for (i = 0; i < trns->var_cnt; i++) 
526     {
527       struct variable **var = &trns->dst_vars[i];
528       const char *name = trns->dst_names[i];
529           
530       *var = dict_lookup_var (dict, name);
531       if (*var == NULL)
532         *var = dict_create_var_assert (dict, name, 0);
533       assert ((*var)->type == trns->dst_type);
534     }
535 }
536 \f
537 /* Data transformation. */
538
539 /* Returns the output mapping in TRNS for an input of VALUE on
540    variable V, or a null pointer if there is no mapping. */
541 static const struct map_out *
542 find_src_numeric (struct recode_trns *trns, double value, struct variable *v)
543 {
544   struct mapping *m;
545
546   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
547     {
548       const struct map_in *in = &m->in;
549       const struct map_out *out = &m->out;
550       bool match;
551       
552       switch (in->type)
553         {
554         case MAP_SINGLE:
555           match = value == in->x.f;
556           break;
557         case MAP_MISSING:
558           match = mv_is_num_user_missing (&v->miss, value);
559           break;
560         case MAP_RANGE:
561           match = value >= in->x.f && value <= in->y.f;
562           break;
563         case MAP_ELSE:
564           match = true;
565           break;
566         default:
567           NOT_REACHED ();
568         }
569
570       if (match)
571         return out;
572     }
573
574   return NULL;
575 }
576
577 /* Returns the output mapping in TRNS for an input of VALUE with
578    the given WIDTH, or a null pointer if there is no mapping. */
579 static const struct map_out *
580 find_src_string (struct recode_trns *trns, const char *value, int width)
581 {
582   struct mapping *m;
583
584   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
585     {
586       const struct map_in *in = &m->in;
587       struct map_out *out = &m->out;
588       bool match;
589       
590       switch (in->type)
591         {
592         case MAP_SINGLE:
593           match = !memcmp (value, in->x.c, width);
594           break;
595         case MAP_ELSE:
596           match = true;
597           break;
598         case MAP_CONVERT:
599           {
600             union value uv;
601
602             msg_disable ();
603             match = data_in (ss_buffer (value, width), FMT_F, 0, 0, &uv, 0);
604             msg_enable ();
605             out->value.f = uv.f;
606             break;
607           }
608         default:
609           NOT_REACHED ();
610         }
611
612       if (match)
613         return out;
614     }
615
616   return NULL;
617 }
618
619 /* Performs RECODE transformation. */
620 static int
621 recode_trns_proc (void *trns_, struct ccase *c, casenumber case_idx UNUSED)
622 {
623   struct recode_trns *trns = trns_;
624   size_t i;
625
626   for (i = 0; i < trns->var_cnt; i++) 
627     {
628       struct variable *src_var = trns->src_vars[i];
629       struct variable *dst_var = trns->dst_vars[i];
630
631       const union value *src_data = case_data (c, src_var->fv);
632       union value *dst_data = case_data_rw (c, dst_var->fv);
633
634       const struct map_out *out;
635
636       if (trns->src_type == NUMERIC) 
637           out = find_src_numeric (trns, src_data->f, src_var);
638       else
639           out = find_src_string (trns, src_data->s, src_var->width);
640
641       if (trns->dst_type == NUMERIC) 
642         {
643           if (out != NULL)
644             dst_data->f = !out->copy_input ? out->value.f : src_data->f; 
645           else if (trns->src_vars != trns->dst_vars)
646             dst_data->f = SYSMIS;
647         }
648       else 
649         {
650           if (out != NULL)
651             {
652               if (!out->copy_input) 
653                 memcpy (dst_data->s, out->value.c, dst_var->width); 
654               else if (trns->src_vars != trns->dst_vars)
655                 buf_copy_rpad (dst_data->s, dst_var->width,
656                                src_data->s, src_var->width); 
657             }
658           else if (trns->src_vars != trns->dst_vars)
659             memset (dst_data->s, ' ', dst_var->width);
660         }
661     }
662
663   return TRNS_CONTINUE;
664 }
665
666 /* Frees a RECODE transformation. */
667 static bool
668 recode_trns_free (void *trns_)
669 {
670   struct recode_trns *trns = trns_;
671   pool_destroy (trns->pool);
672   return true;
673 }