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