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