(parse_map_in): Improve error message when user
[pspp-builds.git] / src / language / xforms / recode.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19 #include <config.h>
20
21 #include <ctype.h>
22 #include <math.h>
23 #include <stdlib.h>
24
25 #include <data/case.h>
26 #include <data/data-in.h>
27 #include <data/dictionary.h>
28 #include <data/procedure.h>
29 #include <data/transformations.h>
30 #include <data/variable.h>
31 #include <language/command.h>
32 #include <language/lexer/lexer.h>
33 #include <language/lexer/variable-parser.h>
34 #include <language/lexer/range-parser.h>
35 #include <libpspp/alloc.h>
36 #include <libpspp/assertion.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     const struct variable **src_vars;   /* Source variables. */
101     const 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 lexer *, struct recode_trns *, const struct dictionary *dict);
111 static bool parse_mappings (struct lexer *, struct recode_trns *);
112 static bool parse_dst_vars (struct lexer *, struct recode_trns *, const struct dictionary *dict);
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 lexer *lexer, 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 lexer *lexer, 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 *, struct dictionary *);
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 (struct lexer *lexer, struct dataset *ds)
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 (lexer, trns, dataset_dict (ds) )
150           || !parse_mappings (lexer, trns)
151           || !parse_dst_vars (lexer, trns, dataset_dict (ds)))
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 == VAR_STRING)
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, dataset_dict (ds));
167
168       /* Done. */
169       add_transformation (ds, 
170                           recode_trns_proc, recode_trns_free, trns);
171     }
172   while (lex_match (lexer, '/'));
173   
174   return lex_end_of_command (lexer);
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 lexer *lexer, 
182                 struct recode_trns *trns, const struct dictionary *dict) 
183 {
184   if (!parse_variables_const (lexer, dict, &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 = var_get_type (trns->src_vars[0]);
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 lexer *lexer, 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 = var_get_width (trns->src_vars[0]);
205   for (i = 1; i < trns->var_cnt; i++) 
206     {
207       size_t var_width = var_get_width (trns->src_vars[i]);
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 (lexer, '('))
218     return false;
219   do
220     {
221       enum var_type dst_type;
222
223       if (!lex_match_id (lexer, "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 (lexer, &in, trns->pool,
236                                  trns->src_type, max_src_width))
237                 return false;
238               add_mapping (trns, &map_allocated, &in);
239               lex_match (lexer, ',');
240             }
241           while (!lex_match (lexer, '='));
242
243           if (!parse_map_out (lexer, trns->pool, &out))
244             return false;
245           dst_type = var_type_from_width (out.width);
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           set_map_out_num (&trns->mappings[trns->map_cnt - 1].out, 0.0);
264               
265           dst_type = VAR_NUMERIC;
266           if (trns->src_type != VAR_STRING
267               || (have_dst_type && trns->dst_type != VAR_NUMERIC)) 
268             {
269               msg (SE, _("CONVERT requires string input values and "
270                          "numeric output values."));
271               return false;
272             }
273         }
274       trns->dst_type = dst_type;
275       have_dst_type = true;
276
277       if (!lex_force_match (lexer, ')'))
278         return false; 
279     }
280   while (lex_match (lexer, '('));
281
282   return true;
283 }
284
285 /* Parses a mapping input value into IN, allocating memory from
286    POOL.  The source value type must be provided as SRC_TYPE and,
287    if string, the maximum width of a string source variable must
288    be provided in MAX_SRC_WIDTH.  Returns true if successful,
289    false on parse error. */
290 static bool
291 parse_map_in (struct lexer *lexer, struct map_in *in, struct pool *pool,
292               enum var_type src_type, size_t max_src_width)
293 {
294   if (lex_match_id (lexer, "ELSE"))
295     set_map_in_generic (in, MAP_ELSE);
296   else if (src_type == VAR_NUMERIC)
297     {
298       if (lex_match_id (lexer, "MISSING"))
299         set_map_in_generic (in, MAP_MISSING);
300       else if (lex_match_id (lexer, "SYSMIS"))
301         set_map_in_generic (in, MAP_SYSMIS);
302       else 
303         {
304           double x, y;
305           if (!parse_num_range (lexer, &x, &y, NULL))
306             return false;
307           set_map_in_num (in, x == y ? MAP_SINGLE : MAP_RANGE, x, y);
308         }
309     }
310   else
311     {
312       if (!lex_force_string (lexer))
313         return false;
314       set_map_in_str (in, pool, lex_tokstr (lexer), max_src_width);
315       lex_get (lexer);
316       if (lex_token (lexer) == T_ID
317           && lex_id_match (ss_cstr ("THRU"), ss_cstr (lex_tokid (lexer)))) 
318         {
319           msg (SE, _("THRU is not allowed with string variables."));
320           return false; 
321         }
322     }
323
324   return true;
325 }
326
327 /* Adds IN to the list of mappings in TRNS.
328    MAP_ALLOCATED is the current number of allocated mappings,
329    which is updated as needed. */
330 static void
331 add_mapping (struct recode_trns *trns,
332              size_t *map_allocated, const struct map_in *in)
333 {
334   struct mapping *m;
335   if (trns->map_cnt >= *map_allocated)
336     trns->mappings = pool_2nrealloc (trns->pool, trns->mappings,
337                                      map_allocated,
338                                      sizeof *trns->mappings);
339   m = &trns->mappings[trns->map_cnt++];
340   m->in = *in;
341 }
342
343 /* Sets IN as a mapping of the given TYPE. */
344 static void
345 set_map_in_generic (struct map_in *in, enum map_in_type type) 
346 {
347   in->type = type;
348 }
349
350 /* Sets IN as a numeric mapping of the given TYPE,
351    with X and Y as the two numeric values. */
352 static void
353 set_map_in_num (struct map_in *in, enum map_in_type type, double x, double y) 
354 {
355   in->type = type;
356   in->x.f = x;
357   in->y.f = y;
358 }
359
360 /* Sets IN as a string mapping, with STRING as the string,
361    allocated from POOL.  The string is padded with spaces on the
362    right to WIDTH characters long. */
363 static void
364 set_map_in_str (struct map_in *in, struct pool *pool,
365                 const struct string *string, size_t width) 
366 {
367   in->type = MAP_SINGLE;
368   in->x.c = pool_alloc_unaligned (pool, width);
369   buf_copy_rpad (in->x.c, width, ds_data (string), ds_length (string));
370 }
371
372 /* Parses a mapping output value into OUT, allocating memory from
373    POOL.  Returns true if successful, false on parse error. */
374 static bool
375 parse_map_out (struct lexer *lexer, struct pool *pool, struct map_out *out)
376 {
377   if (lex_is_number (lexer))
378     {
379       set_map_out_num (out, lex_number (lexer));
380       lex_get (lexer);
381     }
382   else if (lex_match_id (lexer, "SYSMIS"))
383     set_map_out_num (out, SYSMIS);
384   else if (lex_token (lexer) == T_STRING)
385     {
386       set_map_out_str (out, pool, lex_tokstr (lexer));
387       lex_get (lexer);
388     }
389   else if (lex_match_id (lexer, "COPY"))
390     out->copy_input = true;
391   else 
392     {
393       lex_error (lexer, _("expecting output value"));
394       return false;
395     }
396   return true; 
397 }
398
399 /* Sets OUT as a numeric mapping output with the given VALUE. */
400 static void
401 set_map_out_num (struct map_out *out, double value) 
402 {
403   out->copy_input = false;
404   out->value.f = value;
405   out->width = 0;
406 }
407
408 /* Sets OUT as a string mapping output with the given VALUE. */
409 static void
410 set_map_out_str (struct map_out *out, struct pool *pool,
411                  const struct string *value)
412 {
413   const char *string = ds_data (value);
414   size_t length = ds_length (value);
415
416   out->copy_input = false;
417   out->value.c = pool_alloc_unaligned (pool, length);
418   memcpy (out->value.c, string, length);
419   out->width = length;
420 }
421
422 /* Parses a set of target variables into TRNS->dst_vars and
423    TRNS->dst_names. */
424 static bool
425 parse_dst_vars (struct lexer *lexer, struct recode_trns *trns, 
426                 const struct dictionary *dict) 
427 {
428   size_t i;
429   
430   if (lex_match_id (lexer, "INTO"))
431     {
432       size_t name_cnt;
433       size_t i;
434
435       if (!parse_mixed_vars_pool (lexer, dict, trns->pool, 
436                                   &trns->dst_names, &name_cnt,
437                                   PV_NONE))
438         return false;
439
440       if (name_cnt != trns->var_cnt)
441         {
442           msg (SE, _("%u variable(s) cannot be recoded into "
443                      "%u variable(s).  Specify the same number "
444                      "of variables as source and target variables."),
445                (unsigned) trns->var_cnt, (unsigned) name_cnt);
446           return false;
447         }
448
449       trns->dst_vars = pool_nalloc (trns->pool,
450                                     trns->var_cnt, sizeof *trns->dst_vars);
451       for (i = 0; i < trns->var_cnt; i++)
452         {
453           const struct variable *v;
454           v = trns->dst_vars[i] = dict_lookup_var (dict, trns->dst_names[i]);
455           if (v == NULL && trns->dst_type == VAR_STRING) 
456             {
457               msg (SE, _("There is no variable named "
458                          "%s.  (All string variables specified "
459                          "on INTO must already exist.  Use the "
460                          "STRING command to create a string "
461                          "variable.)"),
462                    trns->dst_names[i]);
463               return false;
464             }
465         }
466     }
467   else 
468     {
469       trns->dst_vars = trns->src_vars;
470       if (trns->src_type != trns->dst_type)
471         {
472           msg (SE, _("INTO is required with %s input values "
473                      "and %s output values."),
474                trns->src_type == VAR_NUMERIC ? _("numeric") : _("string"),
475                trns->dst_type == VAR_NUMERIC ? _("numeric") : _("string"));
476           return false;
477         }
478     }
479
480   for (i = 0; i < trns->var_cnt; i++)
481     {
482       const struct variable *v = trns->dst_vars[i];
483       if (v != NULL && var_get_type (v) != trns->dst_type)
484         {
485           msg (SE, _("Type mismatch.  Cannot store %s data in "
486                      "%s variable %s."),
487                trns->dst_type == VAR_STRING ? _("string") : _("numeric"),
488                var_is_alpha (v) ? _("string") : _("numeric"),
489                var_get_name (v));
490           return false;
491         }
492     }
493
494   return true;
495 }
496
497 /* Ensures that all the output values in TRNS are as wide as the
498    widest destination variable. */
499 static void
500 enlarge_dst_widths (struct recode_trns *trns) 
501 {
502   size_t max_dst_width;
503   size_t i;
504
505   max_dst_width = 0;
506   for (i = 0; i < trns->var_cnt; i++)
507     {
508       const struct variable *v = trns->dst_vars[i];
509       if (var_get_width (v) > max_dst_width)
510         max_dst_width = var_get_width (v);
511     }
512
513   for (i = 0; i < trns->map_cnt; i++)
514     {
515       struct map_out *out = &trns->mappings[i].out;
516       if (!out->copy_input && out->width < max_dst_width) 
517         {
518           char *s = pool_alloc_unaligned (trns->pool, max_dst_width + 1);
519           buf_copy_rpad (s, max_dst_width + 1, out->value.c, out->width);
520           out->value.c = s;
521         }
522     }
523 }
524
525 /* Creates destination variables that don't already exist. */
526 static void
527 create_dst_vars (struct recode_trns *trns, struct dictionary *dict)
528 {
529   size_t i;
530
531   for (i = 0; i < trns->var_cnt; i++) 
532     {
533       const struct variable **var = &trns->dst_vars[i];
534       const char *name = trns->dst_names[i];
535           
536       *var = dict_lookup_var (dict, name);
537       if (*var == NULL)
538         *var = dict_create_var_assert (dict, name, 0);
539       assert (var_get_type (*var) == trns->dst_type);
540     }
541 }
542 \f
543 /* Data transformation. */
544
545 /* Returns the output mapping in TRNS for an input of VALUE on
546    variable V, or a null pointer if there is no mapping. */
547 static const struct map_out *
548 find_src_numeric (struct recode_trns *trns, double value, const struct variable *v)
549 {
550   struct mapping *m;
551
552   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
553     {
554       const struct map_in *in = &m->in;
555       const struct map_out *out = &m->out;
556       bool match;
557       
558       switch (in->type)
559         {
560         case MAP_SINGLE:
561           match = value == in->x.f;
562           break;
563         case MAP_MISSING:
564           match = var_is_num_missing (v, value, MV_ANY);
565           break;
566         case MAP_RANGE:
567           match = value >= in->x.f && value <= in->y.f;
568           break;
569         case MAP_SYSMIS:
570           match = value == SYSMIS;
571           break;
572         case MAP_ELSE:
573           match = true;
574           break;
575         default:
576           NOT_REACHED ();
577         }
578
579       if (match)
580         return out;
581     }
582
583   return NULL;
584 }
585
586 /* Returns the output mapping in TRNS for an input of VALUE with
587    the given WIDTH, or a null pointer if there is no mapping. */
588 static const struct map_out *
589 find_src_string (struct recode_trns *trns, const char *value, int width)
590 {
591   struct mapping *m;
592
593   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
594     {
595       const struct map_in *in = &m->in;
596       struct map_out *out = &m->out;
597       bool match;
598       
599       switch (in->type)
600         {
601         case MAP_SINGLE:
602           match = !memcmp (value, in->x.c, width);
603           break;
604         case MAP_ELSE:
605           match = true;
606           break;
607         case MAP_CONVERT:
608           {
609             union value uv;
610
611             msg_disable ();
612             match = data_in (ss_buffer (value, width), FMT_F, 0, 0, &uv, 0);
613             msg_enable ();
614             out->value.f = uv.f;
615             break;
616           }
617         default:
618           NOT_REACHED ();
619         }
620
621       if (match)
622         return out;
623     }
624
625   return NULL;
626 }
627
628 /* Performs RECODE transformation. */
629 static int
630 recode_trns_proc (void *trns_, struct ccase *c, casenumber case_idx UNUSED)
631 {
632   struct recode_trns *trns = trns_;
633   size_t i;
634
635   for (i = 0; i < trns->var_cnt; i++) 
636     {
637       const struct variable *src_var = trns->src_vars[i];
638       const struct variable *dst_var = trns->dst_vars[i];
639
640       const union value *src_data = case_data (c, src_var);
641       union value *dst_data = case_data_rw (c, dst_var);
642
643       const struct map_out *out;
644
645       if (trns->src_type == VAR_NUMERIC) 
646         out = find_src_numeric (trns, src_data->f, src_var);
647       else
648         out = find_src_string (trns, src_data->s, var_get_width (src_var));
649
650       if (trns->dst_type == VAR_NUMERIC) 
651         {
652           if (out != NULL)
653             dst_data->f = !out->copy_input ? out->value.f : src_data->f; 
654           else if (trns->src_vars != trns->dst_vars)
655             dst_data->f = SYSMIS;
656         }
657       else 
658         {
659           if (out != NULL)
660             {
661               if (!out->copy_input) 
662                 memcpy (dst_data->s, out->value.c, var_get_width (dst_var)); 
663               else if (trns->src_vars != trns->dst_vars)
664                 buf_copy_rpad (dst_data->s, var_get_width (dst_var),
665                                src_data->s, var_get_width (src_var)); 
666             }
667           else if (trns->src_vars != trns->dst_vars)
668             memset (dst_data->s, ' ', var_get_width (dst_var));
669         }
670     }
671
672   return TRNS_CONTINUE;
673 }
674
675 /* Frees a RECODE transformation. */
676 static bool
677 recode_trns_free (void *trns_)
678 {
679   struct recode_trns *trns = trns_;
680   pool_destroy (trns->pool);
681   return true;
682 }