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