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