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