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