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