i18n: Introduce C_ENCODING as replacement for LEGACY_NATIVE.
[pspp-builds.git] / src / language / xforms / recode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU 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, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <math.h>
21 #include <stdlib.h>
22
23 #include "data/case.h"
24 #include "data/data-in.h"
25 #include "data/dictionary.h"
26 #include "data/format.h"
27 #include "data/procedure.h"
28 #include "data/transformations.h"
29 #include "data/variable.h"
30 #include "language/command.h"
31 #include "language/lexer/lexer.h"
32 #include "language/lexer/value-parser.h"
33 #include "language/lexer/variable-parser.h"
34 #include "libpspp/assertion.h"
35 #include "libpspp/cast.h"
36 #include "libpspp/compiler.h"
37 #include "libpspp/i18n.h"
38 #include "libpspp/message.h"
39 #include "libpspp/pool.h"
40 #include "libpspp/str.h"
41
42 #include "gl/xalloc.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 /* Describes input values to be mapped. */
61 struct map_in
62   {
63     enum map_in_type type;      /* One of MAP_*. */
64     union value x, y;           /* Source values. */
65   };
66
67 /* Describes the value used as output from a mapping. */
68 struct map_out
69   {
70     bool copy_input;            /* If true, copy input to output. */
71     union value value;          /* If copy_input false, recoded value. */
72     int width;                  /* If copy_input false, output value width. */
73   };
74
75 /* Describes how to recode a single value or range of values into a
76    single value.  */
77 struct mapping
78   {
79     struct map_in in;           /* Input values. */
80     struct map_out out;         /* Output value. */
81   };
82
83 /* RECODE transformation. */
84 struct recode_trns
85   {
86     struct pool *pool;
87
88
89
90     /* Variable types, for convenience. */
91     enum val_type src_type;     /* src_vars[*] type. */
92     enum val_type dst_type;     /* dst_vars[*] type. */
93
94     /* Variables. */
95     const struct variable **src_vars;   /* Source variables. */
96     const struct variable **dst_vars;   /* Destination variables. */
97     const struct dictionary *dst_dict;  /* Dictionary of dst_vars */
98     char **dst_names;           /* Name of dest variables, if they're new. */
99     size_t var_cnt;             /* Number of variables. */
100
101     /* Mappings. */
102     struct mapping *mappings;   /* Value mappings. */
103     size_t map_cnt;             /* Number of mappings. */
104     int max_src_width;          /* Maximum width of src_vars[*]. */
105     int max_dst_width;          /* Maximum width of any map_out in mappings. */
106   };
107
108 static bool parse_src_vars (struct lexer *, struct recode_trns *, const struct dictionary *dict);
109 static bool parse_mappings (struct lexer *, struct recode_trns *);
110 static bool parse_dst_vars (struct lexer *, struct recode_trns *, const struct dictionary *dict);
111
112 static void add_mapping (struct recode_trns *,
113                          size_t *map_allocated, const struct map_in *);
114
115 static bool parse_map_in (struct lexer *lexer, struct map_in *, struct pool *,
116                           enum val_type src_type, size_t max_src_width);
117 static void set_map_in_generic (struct map_in *, enum map_in_type);
118 static void set_map_in_num (struct map_in *, enum map_in_type, double, double);
119 static void set_map_in_str (struct map_in *, struct pool *,
120                             struct substring, size_t width);
121
122 static bool parse_map_out (struct lexer *lexer, struct pool *, struct map_out *);
123 static void set_map_out_num (struct map_out *, double);
124 static void set_map_out_str (struct map_out *, struct pool *,
125                              struct substring);
126
127 static void enlarge_dst_widths (struct recode_trns *);
128 static void create_dst_vars (struct recode_trns *, struct dictionary *);
129
130 static trns_proc_func recode_trns_proc;
131 static trns_free_func recode_trns_free;
132 \f
133 /* Parser. */
134
135 /* Parses the RECODE transformation. */
136 int
137 cmd_recode (struct lexer *lexer, struct dataset *ds)
138 {
139   do
140     {
141       struct recode_trns *trns
142         = pool_create_container (struct recode_trns, pool);
143
144       /* Parse source variable names,
145          then input to output mappings,
146          then destintation variable names. */
147       if (!parse_src_vars (lexer, trns, dataset_dict (ds) )
148           || !parse_mappings (lexer, trns)
149           || !parse_dst_vars (lexer, trns, dataset_dict (ds)))
150         {
151           recode_trns_free (trns);
152           return CMD_FAILURE;
153         }
154
155       /* Ensure that all the output strings are at least as wide
156          as the widest destination variable. */
157       if (trns->dst_type == VAL_STRING)
158         enlarge_dst_widths (trns);
159
160       /* Create destination variables, if needed.
161          This must be the final step; otherwise we'd have to
162          delete destination variables on failure. */
163       trns->dst_dict = dataset_dict (ds);
164       if (trns->src_vars != trns->dst_vars)
165         create_dst_vars (trns, dataset_dict (ds));
166
167       /* Done. */
168       add_transformation (ds,
169                           recode_trns_proc, recode_trns_free, trns);
170     }
171   while (lex_match (lexer, T_SLASH));
172
173   return lex_end_of_command (lexer);
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 lexer *lexer,
181                 struct recode_trns *trns, const struct dictionary *dict)
182 {
183   if (!parse_variables_const (lexer, 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 = var_get_type (trns->src_vars[0]);
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 lexer *lexer, struct recode_trns *trns)
196 {
197   size_t map_allocated;
198   bool have_dst_type;
199   size_t i;
200
201   /* Find length of longest source variable. */
202   trns->max_src_width = var_get_width (trns->src_vars[0]);
203   for (i = 1; i < trns->var_cnt; i++)
204     {
205       size_t var_width = var_get_width (trns->src_vars[i]);
206       if (var_width > trns->max_src_width)
207         trns->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 (lexer, T_LPAREN))
216     return false;
217   do
218     {
219       enum val_type dst_type;
220
221       if (!lex_match_id (lexer, "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
234               if (!parse_map_in (lexer, &in, trns->pool,
235                                  trns->src_type, trns->max_src_width))
236                 return false;
237               add_mapping (trns, &map_allocated, &in);
238               lex_match (lexer, T_COMMA);
239             }
240           while (!lex_match (lexer, T_EQUALS));
241
242           if (!parse_map_out (lexer, trns->pool, &out))
243             return false;
244
245           if (out.copy_input)
246             dst_type = trns->src_type;
247           else
248             dst_type = val_type_from_width (out.width);
249           if (have_dst_type && dst_type != trns->dst_type)
250             {
251               msg (SE, _("Inconsistent target variable types.  "
252                          "Target variables "
253                          "must be all numeric or all string."));
254               return false;
255             }
256
257           for (i = first_map_idx; i < trns->map_cnt; i++)
258             trns->mappings[i].out = out;
259         }
260       else
261         {
262           /* Parse CONVERT as a special case. */
263           struct map_in in;
264           set_map_in_generic (&in, MAP_CONVERT);
265           add_mapping (trns, &map_allocated, &in);
266           set_map_out_num (&trns->mappings[trns->map_cnt - 1].out, 0.0);
267
268           dst_type = VAL_NUMERIC;
269           if (trns->src_type != VAL_STRING
270               || (have_dst_type && trns->dst_type != VAL_NUMERIC))
271             {
272               msg (SE, _("CONVERT requires string input values and "
273                          "numeric output values."));
274               return false;
275             }
276         }
277       trns->dst_type = dst_type;
278       have_dst_type = true;
279
280       if (!lex_force_match (lexer, T_RPAREN))
281         return false;
282     }
283   while (lex_match (lexer, T_LPAREN));
284
285   return true;
286 }
287
288 /* Parses a mapping input value into IN, allocating memory from
289    POOL.  The source value type must be provided as SRC_TYPE and,
290    if string, the maximum width of a string source variable must
291    be provided in MAX_SRC_WIDTH.  Returns true if successful,
292    false on parse error. */
293 static bool
294 parse_map_in (struct lexer *lexer, struct map_in *in, struct pool *pool,
295               enum val_type src_type, size_t max_src_width)
296 {
297
298   if (lex_match_id (lexer, "ELSE"))
299     set_map_in_generic (in, MAP_ELSE);
300   else if (src_type == VAL_NUMERIC)
301     {
302       if (lex_match_id (lexer, "MISSING"))
303         set_map_in_generic (in, MAP_MISSING);
304       else if (lex_match_id (lexer, "SYSMIS"))
305         set_map_in_generic (in, MAP_SYSMIS);
306       else
307         {
308           double x, y;
309           if (!parse_num_range (lexer, &x, &y, NULL))
310             return false;
311           set_map_in_num (in, x == y ? MAP_SINGLE : MAP_RANGE, x, y);
312         }
313     }
314   else
315     {
316       if (lex_match_id (lexer, "MISSING"))
317         set_map_in_generic (in, MAP_MISSING);
318       else if (!lex_force_string (lexer))
319         return false;
320       else 
321         {
322           set_map_in_str (in, pool, lex_tokss (lexer), max_src_width);
323           lex_get (lexer);
324           if (lex_token (lexer) == T_ID
325               && lex_id_match (ss_cstr ("THRU"), lex_tokss (lexer)))
326             {
327               msg (SE, _("THRU is not allowed with string variables."));
328               return false;
329             }
330         }
331     }
332
333   return true;
334 }
335
336 /* Adds IN to the list of mappings in TRNS.
337    MAP_ALLOCATED is the current number of allocated mappings,
338    which is updated as needed. */
339 static void
340 add_mapping (struct recode_trns *trns,
341              size_t *map_allocated, const struct map_in *in)
342 {
343   struct mapping *m;
344   if (trns->map_cnt >= *map_allocated)
345     trns->mappings = pool_2nrealloc (trns->pool, trns->mappings,
346                                      map_allocated,
347                                      sizeof *trns->mappings);
348   m = &trns->mappings[trns->map_cnt++];
349   m->in = *in;
350 }
351
352 /* Sets IN as a mapping of the given TYPE. */
353 static void
354 set_map_in_generic (struct map_in *in, enum map_in_type type)
355 {
356   in->type = type;
357 }
358
359 /* Sets IN as a numeric mapping of the given TYPE,
360    with X and Y as the two numeric values. */
361 static void
362 set_map_in_num (struct map_in *in, enum map_in_type type, double x, double y)
363 {
364   in->type = type;
365   in->x.f = x;
366   in->y.f = y;
367 }
368
369 /* Sets IN as a string mapping, with STRING as the string,
370    allocated from POOL.  The string is padded with spaces on the
371    right to WIDTH characters long. */
372 static void
373 set_map_in_str (struct map_in *in, struct pool *pool,
374                 struct substring string, size_t width)
375 {
376   in->type = MAP_SINGLE;
377   value_init_pool (pool, &in->x, width);
378   value_copy_buf_rpad (&in->x, width,
379                        CHAR_CAST_BUG (uint8_t *, ss_data (string)),
380                        ss_length (string), ' ');
381 }
382
383 /* Parses a mapping output value into OUT, allocating memory from
384    POOL.  Returns true if successful, false on parse error. */
385 static bool
386 parse_map_out (struct lexer *lexer, struct pool *pool, struct map_out *out)
387 {
388   if (lex_is_number (lexer))
389     {
390       set_map_out_num (out, lex_number (lexer));
391       lex_get (lexer);
392     }
393   else if (lex_match_id (lexer, "SYSMIS"))
394     set_map_out_num (out, SYSMIS);
395   else if (lex_is_string (lexer))
396     {
397       set_map_out_str (out, pool, lex_tokss (lexer));
398       lex_get (lexer);
399     }
400   else if (lex_match_id (lexer, "COPY")) 
401     {
402       out->copy_input = true;
403       out->width = 0; 
404     }
405   else
406     {
407       lex_error (lexer, _("expecting output value"));
408       return false;
409     }
410   return true;
411 }
412
413 /* Sets OUT as a numeric mapping output with the given VALUE. */
414 static void
415 set_map_out_num (struct map_out *out, double value)
416 {
417   out->copy_input = false;
418   out->value.f = value;
419   out->width = 0;
420 }
421
422 /* Sets OUT as a string mapping output with the given VALUE. */
423 static void
424 set_map_out_str (struct map_out *out, struct pool *pool,
425                  const struct substring value)
426 {
427   const char *string = ss_data (value);
428   size_t length = ss_length (value);
429
430   if (length == 0)
431     {
432       /* A length of 0 will yield a numeric value, which is not
433          what we want. */
434       string = " ";
435       length = 1;
436     }
437
438   out->copy_input = false;
439   value_init_pool (pool, &out->value, length);
440   memcpy (value_str_rw (&out->value, length), string, length);
441   out->width = length;
442 }
443
444 /* Parses a set of target variables into TRNS->dst_vars and
445    TRNS->dst_names. */
446 static bool
447 parse_dst_vars (struct lexer *lexer, struct recode_trns *trns,
448                 const struct dictionary *dict)
449 {
450   size_t i;
451
452   if (lex_match_id (lexer, "INTO"))
453     {
454       size_t name_cnt;
455       size_t i;
456
457       if (!parse_mixed_vars_pool (lexer, dict, trns->pool,
458                                   &trns->dst_names, &name_cnt,
459                                   PV_NONE))
460         return false;
461
462       if (name_cnt != trns->var_cnt)
463         {
464           msg (SE, _("%zu variable(s) cannot be recoded into "
465                      "%zu variable(s).  Specify the same number "
466                      "of variables as source and target variables."),
467                trns->var_cnt, name_cnt);
468           return false;
469         }
470
471       trns->dst_vars = pool_nalloc (trns->pool,
472                                     trns->var_cnt, sizeof *trns->dst_vars);
473       for (i = 0; i < trns->var_cnt; i++)
474         {
475           const struct variable *v;
476           v = trns->dst_vars[i] = dict_lookup_var (dict, trns->dst_names[i]);
477           if (v == NULL && trns->dst_type == VAL_STRING)
478             {
479               msg (SE, _("There is no variable named "
480                          "%s.  (All string variables specified "
481                          "on INTO must already exist.  Use the "
482                          "STRING command to create a string "
483                          "variable.)"),
484                    trns->dst_names[i]);
485               return false;
486             }
487         }
488
489     }
490   else
491     {
492       trns->dst_vars = trns->src_vars;
493       if (trns->src_type != trns->dst_type)
494         {
495           msg (SE, _("INTO is required with %s input values "
496                      "and %s output values."),
497                trns->src_type == VAL_NUMERIC ? _("numeric") : _("string"),
498                trns->dst_type == VAL_NUMERIC ? _("numeric") : _("string"));
499           return false;
500         }
501     }
502
503   for (i = 0; i < trns->var_cnt; i++)
504     {
505       const struct variable *v = trns->dst_vars[i];
506       if (v != NULL && var_get_type (v) != trns->dst_type)
507         {
508           msg (SE, _("Type mismatch.  Cannot store %s data in "
509                      "%s variable %s."),
510                trns->dst_type == VAL_STRING ? _("string") : _("numeric"),
511                var_is_alpha (v) ? _("string") : _("numeric"),
512                var_get_name (v));
513           return false;
514         }
515     }
516
517   return true;
518 }
519
520 /* Ensures that all the output values in TRNS are as wide as the
521    widest destination variable. */
522 static void
523 enlarge_dst_widths (struct recode_trns *trns)
524 {
525   size_t i;
526
527   trns->max_dst_width = 0;
528   for (i = 0; i < trns->var_cnt; i++)
529     {
530       const struct variable *v = trns->dst_vars[i];
531       if (var_get_width (v) > trns->max_dst_width)
532         trns->max_dst_width = var_get_width (v);
533     }
534
535   for (i = 0; i < trns->map_cnt; i++)
536     {
537       struct map_out *out = &trns->mappings[i].out;
538       if (!out->copy_input)
539         value_resize_pool (trns->pool, &out->value,
540                            out->width, trns->max_dst_width);
541     }
542 }
543
544 /* Creates destination variables that don't already exist. */
545 static void
546 create_dst_vars (struct recode_trns *trns, struct dictionary *dict)
547 {
548   size_t i;
549
550   for (i = 0; i < trns->var_cnt; i++)
551     {
552       const struct variable **var = &trns->dst_vars[i];
553       const char *name = trns->dst_names[i];
554
555       *var = dict_lookup_var (dict, name);
556       if (*var == NULL)
557         *var = dict_create_var_assert (dict, name, 0);
558       assert (var_get_type (*var) == trns->dst_type);
559     }
560 }
561 \f
562 /* Data transformation. */
563
564 /* Returns the output mapping in TRNS for an input of VALUE on
565    variable V, or a null pointer if there is no mapping. */
566 static const struct map_out *
567 find_src_numeric (struct recode_trns *trns, double value, const struct variable *v)
568 {
569   struct mapping *m;
570
571   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
572     {
573       const struct map_in *in = &m->in;
574       const struct map_out *out = &m->out;
575       bool match;
576
577       switch (in->type)
578         {
579         case MAP_SINGLE:
580           match = value == in->x.f;
581           break;
582         case MAP_MISSING:
583           match = var_is_num_missing (v, value, MV_ANY);
584           break;
585         case MAP_RANGE:
586           match = value >= in->x.f && value <= in->y.f;
587           break;
588         case MAP_SYSMIS:
589           match = value == SYSMIS;
590           break;
591         case MAP_ELSE:
592           match = true;
593           break;
594         default:
595           NOT_REACHED ();
596         }
597
598       if (match)
599         return out;
600     }
601
602   return NULL;
603 }
604
605 /* Returns the output mapping in TRNS for an input of VALUE with
606    the given WIDTH, or a null pointer if there is no mapping. */
607 static const struct map_out *
608 find_src_string (struct recode_trns *trns, const uint8_t *value,
609                  const struct variable *src_var)
610 {
611   const char *encoding = dict_get_encoding (trns->dst_dict);
612   int width = var_get_width (src_var);
613   struct mapping *m;
614
615   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
616     {
617       const struct map_in *in = &m->in;
618       struct map_out *out = &m->out;
619       bool match;
620
621       switch (in->type)
622         {
623         case MAP_SINGLE:
624           match = !memcmp (value, value_str (&in->x, trns->max_src_width),
625                            width);
626           break;
627         case MAP_ELSE:
628           match = true;
629           break;
630         case MAP_CONVERT:
631           {
632             union value uv;
633             char *error;
634
635             error = data_in (ss_buffer (CHAR_CAST_BUG (char *, value), width),
636                              C_ENCODING, FMT_F, &uv, 0, encoding);
637             match = error == NULL;
638             free (error);
639
640             out->value.f = uv.f;
641             break;
642           }
643         case MAP_MISSING:
644           match = var_is_str_missing (src_var, value, MV_ANY);
645           break;
646         default:
647           NOT_REACHED ();
648         }
649
650       if (match)
651         return out;
652     }
653
654   return NULL;
655 }
656
657 /* Performs RECODE transformation. */
658 static int
659 recode_trns_proc (void *trns_, struct ccase **c, casenumber case_idx UNUSED)
660 {
661   struct recode_trns *trns = trns_;
662   size_t i;
663
664   *c = case_unshare (*c);
665   for (i = 0; i < trns->var_cnt; i++)
666     {
667       const struct variable *src_var = trns->src_vars[i];
668       const struct variable *dst_var = trns->dst_vars[i];
669       const struct map_out *out;
670
671       if (trns->src_type == VAL_NUMERIC)
672         out = find_src_numeric (trns, case_num (*c, src_var), src_var);
673       else
674         out = find_src_string (trns, case_str (*c, src_var), src_var);
675
676       if (trns->dst_type == VAL_NUMERIC)
677         {
678           double *dst = &case_data_rw (*c, dst_var)->f;
679           if (out != NULL)
680             *dst = !out->copy_input ? out->value.f : case_num (*c, src_var);
681           else if (trns->src_vars != trns->dst_vars)
682             *dst = SYSMIS;
683         }
684       else
685         {
686           char *dst = CHAR_CAST_BUG (char *, case_str_rw (*c, dst_var));
687           if (out != NULL)
688             {
689               if (!out->copy_input)
690                 memcpy (dst, value_str (&out->value, trns->max_dst_width),
691                         var_get_width (dst_var));
692               else if (trns->src_vars != trns->dst_vars)
693                 {
694                   union value *dst_data = case_data_rw (*c, dst_var);
695                   const union value *src_data = case_data (*c, src_var);
696                   value_copy_rpad (dst_data, var_get_width (dst_var),
697                                    src_data, var_get_width (src_var), ' ');
698                 }
699             }
700           else if (trns->src_vars != trns->dst_vars)
701             memset (dst, ' ', var_get_width (dst_var));
702         }
703     }
704
705   return TRNS_CONTINUE;
706 }
707
708 /* Frees a RECODE transformation. */
709 static bool
710 recode_trns_free (void *trns_)
711 {
712   struct recode_trns *trns = trns_;
713   pool_destroy (trns->pool);
714   return true;
715 }