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