77543ca7a8caa5c55055456266220d0173708061
[pspp-builds.git] / 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/dictionary.h"
26 #include "data/format.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/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 void 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         enlarge_dst_widths (trns);
161
162       /* Create destination variables, if needed.
163          This must be the final step; otherwise we'd have to
164          delete destination variables on failure. */
165       trns->dst_dict = dict;
166       if (trns->src_vars != trns->dst_vars)
167         create_dst_vars (trns, dict);
168
169       /* Done. */
170       add_transformation (ds,
171                           recode_trns_proc, recode_trns_free, trns);
172     }
173   while (lex_match (lexer, T_SLASH));
174
175   return CMD_SUCCESS;
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_const (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 = var_get_type (trns->src_vars[0]);
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                 const char *dict_encoding)
199 {
200   size_t map_allocated;
201   bool have_dst_type;
202   size_t i;
203
204   /* Find length of longest source variable. */
205   trns->max_src_width = var_get_width (trns->src_vars[0]);
206   for (i = 1; i < trns->var_cnt; i++)
207     {
208       size_t var_width = var_get_width (trns->src_vars[i]);
209       if (var_width > trns->max_src_width)
210         trns->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, T_LPAREN))
219     return false;
220   do
221     {
222       enum val_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
237               if (!parse_map_in (lexer, &in, trns->pool,
238                                  trns->src_type, trns->max_src_width,
239                                  dict_encoding))
240                 return false;
241               add_mapping (trns, &map_allocated, &in);
242               lex_match (lexer, T_COMMA);
243             }
244           while (!lex_match (lexer, T_EQUALS));
245
246           if (!parse_map_out (lexer, trns->pool, &out))
247             return false;
248
249           if (out.copy_input)
250             dst_type = trns->src_type;
251           else
252             dst_type = val_type_from_width (out.width);
253           if (have_dst_type && dst_type != trns->dst_type)
254             {
255               msg (SE, _("Inconsistent target variable types.  "
256                          "Target variables "
257                          "must be all numeric or all string."));
258               return false;
259             }
260
261           for (i = first_map_idx; i < trns->map_cnt; i++)
262             trns->mappings[i].out = out;
263         }
264       else
265         {
266           /* Parse CONVERT as a special case. */
267           struct map_in in;
268           set_map_in_generic (&in, MAP_CONVERT);
269           add_mapping (trns, &map_allocated, &in);
270           set_map_out_num (&trns->mappings[trns->map_cnt - 1].out, 0.0);
271
272           dst_type = VAL_NUMERIC;
273           if (trns->src_type != VAL_STRING
274               || (have_dst_type && trns->dst_type != VAL_NUMERIC))
275             {
276               msg (SE, _("CONVERT requires string input values and "
277                          "numeric output values."));
278               return false;
279             }
280         }
281       trns->dst_type = dst_type;
282       have_dst_type = true;
283
284       if (!lex_force_match (lexer, T_RPAREN))
285         return false;
286     }
287   while (lex_match (lexer, T_LPAREN));
288
289   return true;
290 }
291
292 /* Parses a mapping input value into IN, allocating memory from
293    POOL.  The source value type must be provided as SRC_TYPE and,
294    if string, the maximum width of a string source variable must
295    be provided in MAX_SRC_WIDTH.  Returns true if successful,
296    false on parse error. */
297 static bool
298 parse_map_in (struct lexer *lexer, struct map_in *in, struct pool *pool,
299               enum val_type src_type, size_t max_src_width,
300               const char *dict_encoding)
301 {
302
303   if (lex_match_id (lexer, "ELSE"))
304     set_map_in_generic (in, MAP_ELSE);
305   else if (src_type == VAL_NUMERIC)
306     {
307       if (lex_match_id (lexer, "MISSING"))
308         set_map_in_generic (in, MAP_MISSING);
309       else if (lex_match_id (lexer, "SYSMIS"))
310         set_map_in_generic (in, MAP_SYSMIS);
311       else
312         {
313           double x, y;
314           if (!parse_num_range (lexer, &x, &y, NULL))
315             return false;
316           set_map_in_num (in, x == y ? MAP_SINGLE : MAP_RANGE, x, y);
317         }
318     }
319   else
320     {
321       if (lex_match_id (lexer, "MISSING"))
322         set_map_in_generic (in, MAP_MISSING);
323       else if (!lex_force_string (lexer))
324         return false;
325       else 
326         {
327           set_map_in_str (in, pool, lex_tokss (lexer), max_src_width,
328                           dict_encoding);
329           lex_get (lexer);
330           if (lex_token (lexer) == T_ID
331               && lex_id_match (ss_cstr ("THRU"), lex_tokss (lexer)))
332             {
333               msg (SE, _("THRU is not allowed with string variables."));
334               return false;
335             }
336         }
337     }
338
339   return true;
340 }
341
342 /* Adds IN to the list of mappings in TRNS.
343    MAP_ALLOCATED is the current number of allocated mappings,
344    which is updated as needed. */
345 static void
346 add_mapping (struct recode_trns *trns,
347              size_t *map_allocated, const struct map_in *in)
348 {
349   struct mapping *m;
350   if (trns->map_cnt >= *map_allocated)
351     trns->mappings = pool_2nrealloc (trns->pool, trns->mappings,
352                                      map_allocated,
353                                      sizeof *trns->mappings);
354   m = &trns->mappings[trns->map_cnt++];
355   m->in = *in;
356 }
357
358 /* Sets IN as a mapping of the given TYPE. */
359 static void
360 set_map_in_generic (struct map_in *in, enum map_in_type type)
361 {
362   in->type = type;
363 }
364
365 /* Sets IN as a numeric mapping of the given TYPE,
366    with X and Y as the two numeric values. */
367 static void
368 set_map_in_num (struct map_in *in, enum map_in_type type, double x, double y)
369 {
370   in->type = type;
371   in->x.f = x;
372   in->y.f = y;
373 }
374
375 /* Sets IN as a string mapping, with STRING as the string,
376    allocated from POOL.  The string is padded with spaces on the
377    right to WIDTH characters long. */
378 static void
379 set_map_in_str (struct map_in *in, struct pool *pool,
380                 struct substring string, size_t width,
381                 const char *dict_encoding)
382 {
383   char *s = recode_string (dict_encoding, "UTF-8",
384                            ss_data (string), ss_length (string));
385   in->type = MAP_SINGLE;
386   value_init_pool (pool, &in->x, width);
387   value_copy_buf_rpad (&in->x, width,
388                        CHAR_CAST (uint8_t *, s), strlen (s), ' ');
389   free (s);
390 }
391
392 /* Parses a mapping output value into OUT, allocating memory from
393    POOL.  Returns true if successful, false on parse error. */
394 static bool
395 parse_map_out (struct lexer *lexer, struct pool *pool, struct map_out *out)
396 {
397   if (lex_is_number (lexer))
398     {
399       set_map_out_num (out, lex_number (lexer));
400       lex_get (lexer);
401     }
402   else if (lex_match_id (lexer, "SYSMIS"))
403     set_map_out_num (out, SYSMIS);
404   else if (lex_is_string (lexer))
405     {
406       set_map_out_str (out, pool, lex_tokss (lexer));
407       lex_get (lexer);
408     }
409   else if (lex_match_id (lexer, "COPY")) 
410     {
411       out->copy_input = true;
412       out->width = 0; 
413     }
414   else
415     {
416       lex_error (lexer, _("expecting output value"));
417       return false;
418     }
419   return true;
420 }
421
422 /* Sets OUT as a numeric mapping output with the given VALUE. */
423 static void
424 set_map_out_num (struct map_out *out, double value)
425 {
426   out->copy_input = false;
427   out->value.f = value;
428   out->width = 0;
429 }
430
431 /* Sets OUT as a string mapping output with the given VALUE. */
432 static void
433 set_map_out_str (struct map_out *out, struct pool *pool,
434                  const struct substring value)
435 {
436   const char *string = ss_data (value);
437   size_t length = ss_length (value);
438
439   if (length == 0)
440     {
441       /* A length of 0 will yield a numeric value, which is not
442          what we want. */
443       string = " ";
444       length = 1;
445     }
446
447   out->copy_input = false;
448   value_init_pool (pool, &out->value, length);
449   memcpy (value_str_rw (&out->value, length), string, length);
450   out->width = length;
451 }
452
453 /* Parses a set of target variables into TRNS->dst_vars and
454    TRNS->dst_names. */
455 static bool
456 parse_dst_vars (struct lexer *lexer, struct recode_trns *trns,
457                 const struct dictionary *dict)
458 {
459   size_t i;
460
461   if (lex_match_id (lexer, "INTO"))
462     {
463       size_t name_cnt;
464       size_t i;
465
466       if (!parse_mixed_vars_pool (lexer, dict, trns->pool,
467                                   &trns->dst_names, &name_cnt,
468                                   PV_NONE))
469         return false;
470
471       if (name_cnt != trns->var_cnt)
472         {
473           msg (SE, _("%zu variable(s) cannot be recoded into "
474                      "%zu variable(s).  Specify the same number "
475                      "of variables as source and target variables."),
476                trns->var_cnt, name_cnt);
477           return false;
478         }
479
480       trns->dst_vars = pool_nalloc (trns->pool,
481                                     trns->var_cnt, sizeof *trns->dst_vars);
482       for (i = 0; i < trns->var_cnt; i++)
483         {
484           const struct variable *v;
485           v = trns->dst_vars[i] = dict_lookup_var (dict, trns->dst_names[i]);
486           if (v == NULL && trns->dst_type == VAL_STRING)
487             {
488               msg (SE, _("There is no variable named "
489                          "%s.  (All string variables specified "
490                          "on INTO must already exist.  Use the "
491                          "STRING command to create a string "
492                          "variable.)"),
493                    trns->dst_names[i]);
494               return false;
495             }
496         }
497
498     }
499   else
500     {
501       trns->dst_vars = trns->src_vars;
502       if (trns->src_type != trns->dst_type)
503         {
504           msg (SE, _("INTO is required with %s input values "
505                      "and %s output values."),
506                trns->src_type == VAL_NUMERIC ? _("numeric") : _("string"),
507                trns->dst_type == VAL_NUMERIC ? _("numeric") : _("string"));
508           return false;
509         }
510     }
511
512   for (i = 0; i < trns->var_cnt; i++)
513     {
514       const struct variable *v = trns->dst_vars[i];
515       if (v != NULL && var_get_type (v) != trns->dst_type)
516         {
517           msg (SE, _("Type mismatch.  Cannot store %s data in "
518                      "%s variable %s."),
519                trns->dst_type == VAL_STRING ? _("string") : _("numeric"),
520                var_is_alpha (v) ? _("string") : _("numeric"),
521                var_get_name (v));
522           return false;
523         }
524     }
525
526   return true;
527 }
528
529 /* Ensures that all the output values in TRNS are as wide as the
530    widest destination variable. */
531 static void
532 enlarge_dst_widths (struct recode_trns *trns)
533 {
534   size_t i;
535
536   trns->max_dst_width = 0;
537   for (i = 0; i < trns->var_cnt; i++)
538     {
539       const struct variable *v = trns->dst_vars[i];
540       if (var_get_width (v) > trns->max_dst_width)
541         trns->max_dst_width = var_get_width (v);
542     }
543
544   for (i = 0; i < trns->map_cnt; i++)
545     {
546       struct map_out *out = &trns->mappings[i].out;
547       if (!out->copy_input)
548         value_resize_pool (trns->pool, &out->value,
549                            out->width, trns->max_dst_width);
550     }
551 }
552
553 /* Creates destination variables that don't already exist. */
554 static void
555 create_dst_vars (struct recode_trns *trns, struct dictionary *dict)
556 {
557   size_t i;
558
559   for (i = 0; i < trns->var_cnt; i++)
560     {
561       const struct variable **var = &trns->dst_vars[i];
562       const char *name = trns->dst_names[i];
563
564       *var = dict_lookup_var (dict, name);
565       if (*var == NULL)
566         *var = dict_create_var_assert (dict, name, 0);
567       assert (var_get_type (*var) == trns->dst_type);
568     }
569 }
570 \f
571 /* Data transformation. */
572
573 /* Returns the output mapping in TRNS for an input of VALUE on
574    variable V, or a null pointer if there is no mapping. */
575 static const struct map_out *
576 find_src_numeric (struct recode_trns *trns, double value, const struct variable *v)
577 {
578   struct mapping *m;
579
580   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
581     {
582       const struct map_in *in = &m->in;
583       const struct map_out *out = &m->out;
584       bool match;
585
586       switch (in->type)
587         {
588         case MAP_SINGLE:
589           match = value == in->x.f;
590           break;
591         case MAP_MISSING:
592           match = var_is_num_missing (v, value, MV_ANY);
593           break;
594         case MAP_RANGE:
595           match = value >= in->x.f && value <= in->y.f;
596           break;
597         case MAP_SYSMIS:
598           match = value == SYSMIS;
599           break;
600         case MAP_ELSE:
601           match = true;
602           break;
603         default:
604           NOT_REACHED ();
605         }
606
607       if (match)
608         return out;
609     }
610
611   return NULL;
612 }
613
614 /* Returns the output mapping in TRNS for an input of VALUE with
615    the given WIDTH, or a null pointer if there is no mapping. */
616 static const struct map_out *
617 find_src_string (struct recode_trns *trns, const uint8_t *value,
618                  const struct variable *src_var)
619 {
620   const char *encoding = dict_get_encoding (trns->dst_dict);
621   int width = var_get_width (src_var);
622   struct mapping *m;
623
624   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
625     {
626       const struct map_in *in = &m->in;
627       struct map_out *out = &m->out;
628       bool match;
629
630       switch (in->type)
631         {
632         case MAP_SINGLE:
633           match = !memcmp (value, value_str (&in->x, trns->max_src_width),
634                            width);
635           break;
636         case MAP_ELSE:
637           match = true;
638           break;
639         case MAP_CONVERT:
640           {
641             union value uv;
642             char *error;
643
644             error = data_in (ss_buffer (CHAR_CAST_BUG (char *, value), width),
645                              C_ENCODING, FMT_F, &uv, 0, encoding);
646             match = error == NULL;
647             free (error);
648
649             out->value.f = uv.f;
650             break;
651           }
652         case MAP_MISSING:
653           match = var_is_str_missing (src_var, value, MV_ANY);
654           break;
655         default:
656           NOT_REACHED ();
657         }
658
659       if (match)
660         return out;
661     }
662
663   return NULL;
664 }
665
666 /* Performs RECODE transformation. */
667 static int
668 recode_trns_proc (void *trns_, struct ccase **c, casenumber case_idx UNUSED)
669 {
670   struct recode_trns *trns = trns_;
671   size_t i;
672
673   *c = case_unshare (*c);
674   for (i = 0; i < trns->var_cnt; i++)
675     {
676       const struct variable *src_var = trns->src_vars[i];
677       const struct variable *dst_var = trns->dst_vars[i];
678       const struct map_out *out;
679
680       if (trns->src_type == VAL_NUMERIC)
681         out = find_src_numeric (trns, case_num (*c, src_var), src_var);
682       else
683         out = find_src_string (trns, case_str (*c, src_var), src_var);
684
685       if (trns->dst_type == VAL_NUMERIC)
686         {
687           double *dst = &case_data_rw (*c, dst_var)->f;
688           if (out != NULL)
689             *dst = !out->copy_input ? out->value.f : case_num (*c, src_var);
690           else if (trns->src_vars != trns->dst_vars)
691             *dst = SYSMIS;
692         }
693       else
694         {
695           char *dst = CHAR_CAST_BUG (char *, case_str_rw (*c, dst_var));
696           if (out != NULL)
697             {
698               if (!out->copy_input)
699                 memcpy (dst, value_str (&out->value, trns->max_dst_width),
700                         var_get_width (dst_var));
701               else if (trns->src_vars != trns->dst_vars)
702                 {
703                   union value *dst_data = case_data_rw (*c, dst_var);
704                   const union value *src_data = case_data (*c, src_var);
705                   value_copy_rpad (dst_data, var_get_width (dst_var),
706                                    src_data, var_get_width (src_var), ' ');
707                 }
708             }
709           else if (trns->src_vars != trns->dst_vars)
710             memset (dst, ' ', var_get_width (dst_var));
711         }
712     }
713
714   return TRNS_CONTINUE;
715 }
716
717 /* Frees a RECODE transformation. */
718 static bool
719 recode_trns_free (void *trns_)
720 {
721   struct recode_trns *trns = trns_;
722   pool_destroy (trns->pool);
723   return true;
724 }