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