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