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