1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2009, 2010 Free Software Foundation, Inc.
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.
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.
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/>. */
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/message.h"
38 #include "libpspp/pool.h"
39 #include "libpspp/str.h"
41 #include "gl/xalloc.h"
44 #define _(msgid) gettext (msgid)
48 /* Type of source value for RECODE. */
51 MAP_SINGLE, /* Specific value. */
52 MAP_RANGE, /* Range of values. */
53 MAP_SYSMIS, /* System missing value. */
54 MAP_MISSING, /* Any missing value. */
55 MAP_ELSE, /* Any value. */
56 MAP_CONVERT /* "123" => 123. */
59 /* Describes input values to be mapped. */
62 enum map_in_type type; /* One of MAP_*. */
63 union value x, y; /* Source values. */
66 /* Describes the value used as output from a mapping. */
69 bool copy_input; /* If true, copy input to output. */
70 union value value; /* If copy_input false, recoded value. */
71 int width; /* If copy_input false, output value width. */
74 /* Describes how to recode a single value or range of values into a
78 struct map_in in; /* Input values. */
79 struct map_out out; /* Output value. */
82 /* RECODE transformation. */
89 /* Variable types, for convenience. */
90 enum val_type src_type; /* src_vars[*] type. */
91 enum val_type dst_type; /* dst_vars[*] type. */
94 const struct variable **src_vars; /* Source variables. */
95 const struct variable **dst_vars; /* Destination variables. */
96 const struct dictionary *dst_dict; /* Dictionary of dst_vars */
97 char **dst_names; /* Name of dest variables, if they're new. */
98 size_t var_cnt; /* Number of variables. */
101 struct mapping *mappings; /* Value mappings. */
102 size_t map_cnt; /* Number of mappings. */
103 int max_src_width; /* Maximum width of src_vars[*]. */
104 int max_dst_width; /* Maximum width of any map_out in mappings. */
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);
111 static void add_mapping (struct recode_trns *,
112 size_t *map_allocated, const struct map_in *);
114 static bool parse_map_in (struct lexer *lexer, struct map_in *, struct pool *,
115 enum val_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 struct substring, size_t width);
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 *,
126 static void enlarge_dst_widths (struct recode_trns *);
127 static void create_dst_vars (struct recode_trns *, struct dictionary *);
129 static trns_proc_func recode_trns_proc;
130 static trns_free_func recode_trns_free;
134 /* Parses the RECODE transformation. */
136 cmd_recode (struct lexer *lexer, struct dataset *ds)
140 struct recode_trns *trns
141 = pool_create_container (struct recode_trns, pool);
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)))
150 recode_trns_free (trns);
154 /* Ensure that all the output strings are at least as wide
155 as the widest destination variable. */
156 if (trns->dst_type == VAL_STRING)
157 enlarge_dst_widths (trns);
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 trns->dst_dict = dataset_dict (ds);
163 if (trns->src_vars != trns->dst_vars)
164 create_dst_vars (trns, dataset_dict (ds));
167 add_transformation (ds,
168 recode_trns_proc, recode_trns_free, trns);
170 while (lex_match (lexer, T_SLASH));
172 return lex_end_of_command (lexer);
175 /* Parses a set of variables to recode into TRNS->src_vars and
176 TRNS->var_cnt. Sets TRNS->src_type. Returns true if
177 successful, false on parse error. */
179 parse_src_vars (struct lexer *lexer,
180 struct recode_trns *trns, const struct dictionary *dict)
182 if (!parse_variables_const (lexer, dict, &trns->src_vars, &trns->var_cnt,
185 pool_register (trns->pool, free, trns->src_vars);
186 trns->src_type = var_get_type (trns->src_vars[0]);
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. */
194 parse_mappings (struct lexer *lexer, struct recode_trns *trns)
196 size_t map_allocated;
200 /* Find length of longest source variable. */
201 trns->max_src_width = var_get_width (trns->src_vars[0]);
202 for (i = 1; i < trns->var_cnt; i++)
204 size_t var_width = var_get_width (trns->src_vars[i]);
205 if (var_width > trns->max_src_width)
206 trns->max_src_width = var_width;
209 /* Parse the mappings in parentheses. */
210 trns->mappings = NULL;
213 have_dst_type = false;
214 if (!lex_force_match (lexer, T_LPAREN))
218 enum val_type dst_type;
220 if (!lex_match_id (lexer, "CONVERT"))
223 size_t first_map_idx;
226 first_map_idx = trns->map_cnt;
228 /* Parse source specifications. */
233 if (!parse_map_in (lexer, &in, trns->pool,
234 trns->src_type, trns->max_src_width))
236 add_mapping (trns, &map_allocated, &in);
237 lex_match (lexer, T_COMMA);
239 while (!lex_match (lexer, T_EQUALS));
241 if (!parse_map_out (lexer, trns->pool, &out))
245 dst_type = trns->src_type;
247 dst_type = val_type_from_width (out.width);
248 if (have_dst_type && dst_type != trns->dst_type)
250 msg (SE, _("Inconsistent target variable types. "
252 "must be all numeric or all string."));
256 for (i = first_map_idx; i < trns->map_cnt; i++)
257 trns->mappings[i].out = out;
261 /* Parse CONVERT as a special case. */
263 set_map_in_generic (&in, MAP_CONVERT);
264 add_mapping (trns, &map_allocated, &in);
265 set_map_out_num (&trns->mappings[trns->map_cnt - 1].out, 0.0);
267 dst_type = VAL_NUMERIC;
268 if (trns->src_type != VAL_STRING
269 || (have_dst_type && trns->dst_type != VAL_NUMERIC))
271 msg (SE, _("CONVERT requires string input values and "
272 "numeric output values."));
276 trns->dst_type = dst_type;
277 have_dst_type = true;
279 if (!lex_force_match (lexer, T_RPAREN))
282 while (lex_match (lexer, T_LPAREN));
287 /* Parses a mapping input value into IN, allocating memory from
288 POOL. The source value type must be provided as SRC_TYPE and,
289 if string, the maximum width of a string source variable must
290 be provided in MAX_SRC_WIDTH. Returns true if successful,
291 false on parse error. */
293 parse_map_in (struct lexer *lexer, struct map_in *in, struct pool *pool,
294 enum val_type src_type, size_t max_src_width)
297 if (lex_match_id (lexer, "ELSE"))
298 set_map_in_generic (in, MAP_ELSE);
299 else if (src_type == VAL_NUMERIC)
301 if (lex_match_id (lexer, "MISSING"))
302 set_map_in_generic (in, MAP_MISSING);
303 else if (lex_match_id (lexer, "SYSMIS"))
304 set_map_in_generic (in, MAP_SYSMIS);
308 if (!parse_num_range (lexer, &x, &y, NULL))
310 set_map_in_num (in, x == y ? MAP_SINGLE : MAP_RANGE, x, y);
315 if (lex_match_id (lexer, "MISSING"))
316 set_map_in_generic (in, MAP_MISSING);
317 else if (!lex_force_string (lexer))
321 set_map_in_str (in, pool, lex_tokss (lexer), max_src_width);
323 if (lex_token (lexer) == T_ID
324 && lex_id_match (ss_cstr ("THRU"), lex_tokss (lexer)))
326 msg (SE, _("THRU is not allowed with string variables."));
335 /* Adds IN to the list of mappings in TRNS.
336 MAP_ALLOCATED is the current number of allocated mappings,
337 which is updated as needed. */
339 add_mapping (struct recode_trns *trns,
340 size_t *map_allocated, const struct map_in *in)
343 if (trns->map_cnt >= *map_allocated)
344 trns->mappings = pool_2nrealloc (trns->pool, trns->mappings,
346 sizeof *trns->mappings);
347 m = &trns->mappings[trns->map_cnt++];
351 /* Sets IN as a mapping of the given TYPE. */
353 set_map_in_generic (struct map_in *in, enum map_in_type type)
358 /* Sets IN as a numeric mapping of the given TYPE,
359 with X and Y as the two numeric values. */
361 set_map_in_num (struct map_in *in, enum map_in_type type, double x, double y)
368 /* Sets IN as a string mapping, with STRING as the string,
369 allocated from POOL. The string is padded with spaces on the
370 right to WIDTH characters long. */
372 set_map_in_str (struct map_in *in, struct pool *pool,
373 struct substring string, size_t width)
375 in->type = MAP_SINGLE;
376 value_init_pool (pool, &in->x, width);
377 value_copy_buf_rpad (&in->x, width,
378 CHAR_CAST_BUG (uint8_t *, ss_data (string)),
379 ss_length (string), ' ');
382 /* Parses a mapping output value into OUT, allocating memory from
383 POOL. Returns true if successful, false on parse error. */
385 parse_map_out (struct lexer *lexer, struct pool *pool, struct map_out *out)
387 if (lex_is_number (lexer))
389 set_map_out_num (out, lex_number (lexer));
392 else if (lex_match_id (lexer, "SYSMIS"))
393 set_map_out_num (out, SYSMIS);
394 else if (lex_is_string (lexer))
396 set_map_out_str (out, pool, lex_tokss (lexer));
399 else if (lex_match_id (lexer, "COPY"))
401 out->copy_input = true;
406 lex_error (lexer, _("expecting output value"));
412 /* Sets OUT as a numeric mapping output with the given VALUE. */
414 set_map_out_num (struct map_out *out, double value)
416 out->copy_input = false;
417 out->value.f = value;
421 /* Sets OUT as a string mapping output with the given VALUE. */
423 set_map_out_str (struct map_out *out, struct pool *pool,
424 const struct substring value)
426 const char *string = ss_data (value);
427 size_t length = ss_length (value);
431 /* A length of 0 will yield a numeric value, which is not
437 out->copy_input = false;
438 value_init_pool (pool, &out->value, length);
439 memcpy (value_str_rw (&out->value, length), string, length);
443 /* Parses a set of target variables into TRNS->dst_vars and
446 parse_dst_vars (struct lexer *lexer, struct recode_trns *trns,
447 const struct dictionary *dict)
451 if (lex_match_id (lexer, "INTO"))
456 if (!parse_mixed_vars_pool (lexer, dict, trns->pool,
457 &trns->dst_names, &name_cnt,
461 if (name_cnt != trns->var_cnt)
463 msg (SE, _("%zu variable(s) cannot be recoded into "
464 "%zu variable(s). Specify the same number "
465 "of variables as source and target variables."),
466 trns->var_cnt, name_cnt);
470 trns->dst_vars = pool_nalloc (trns->pool,
471 trns->var_cnt, sizeof *trns->dst_vars);
472 for (i = 0; i < trns->var_cnt; i++)
474 const struct variable *v;
475 v = trns->dst_vars[i] = dict_lookup_var (dict, trns->dst_names[i]);
476 if (v == NULL && trns->dst_type == VAL_STRING)
478 msg (SE, _("There is no variable named "
479 "%s. (All string variables specified "
480 "on INTO must already exist. Use the "
481 "STRING command to create a string "
491 trns->dst_vars = trns->src_vars;
492 if (trns->src_type != trns->dst_type)
494 msg (SE, _("INTO is required with %s input values "
495 "and %s output values."),
496 trns->src_type == VAL_NUMERIC ? _("numeric") : _("string"),
497 trns->dst_type == VAL_NUMERIC ? _("numeric") : _("string"));
502 for (i = 0; i < trns->var_cnt; i++)
504 const struct variable *v = trns->dst_vars[i];
505 if (v != NULL && var_get_type (v) != trns->dst_type)
507 msg (SE, _("Type mismatch. Cannot store %s data in "
509 trns->dst_type == VAL_STRING ? _("string") : _("numeric"),
510 var_is_alpha (v) ? _("string") : _("numeric"),
519 /* Ensures that all the output values in TRNS are as wide as the
520 widest destination variable. */
522 enlarge_dst_widths (struct recode_trns *trns)
526 trns->max_dst_width = 0;
527 for (i = 0; i < trns->var_cnt; i++)
529 const struct variable *v = trns->dst_vars[i];
530 if (var_get_width (v) > trns->max_dst_width)
531 trns->max_dst_width = var_get_width (v);
534 for (i = 0; i < trns->map_cnt; i++)
536 struct map_out *out = &trns->mappings[i].out;
537 if (!out->copy_input)
538 value_resize_pool (trns->pool, &out->value,
539 out->width, trns->max_dst_width);
543 /* Creates destination variables that don't already exist. */
545 create_dst_vars (struct recode_trns *trns, struct dictionary *dict)
549 for (i = 0; i < trns->var_cnt; i++)
551 const struct variable **var = &trns->dst_vars[i];
552 const char *name = trns->dst_names[i];
554 *var = dict_lookup_var (dict, name);
556 *var = dict_create_var_assert (dict, name, 0);
557 assert (var_get_type (*var) == trns->dst_type);
561 /* Data transformation. */
563 /* Returns the output mapping in TRNS for an input of VALUE on
564 variable V, or a null pointer if there is no mapping. */
565 static const struct map_out *
566 find_src_numeric (struct recode_trns *trns, double value, const struct variable *v)
570 for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
572 const struct map_in *in = &m->in;
573 const struct map_out *out = &m->out;
579 match = value == in->x.f;
582 match = var_is_num_missing (v, value, MV_ANY);
585 match = value >= in->x.f && value <= in->y.f;
588 match = value == SYSMIS;
604 /* Returns the output mapping in TRNS for an input of VALUE with
605 the given WIDTH, or a null pointer if there is no mapping. */
606 static const struct map_out *
607 find_src_string (struct recode_trns *trns, const uint8_t *value,
608 const struct variable *src_var)
610 const char *encoding = dict_get_encoding (trns->dst_dict);
611 int width = var_get_width (src_var);
614 for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
616 const struct map_in *in = &m->in;
617 struct map_out *out = &m->out;
623 match = !memcmp (value, value_str (&in->x, trns->max_src_width),
634 error = data_in (ss_buffer (CHAR_CAST_BUG (char *, value), width),
635 LEGACY_NATIVE, FMT_F, &uv, 0, encoding);
636 match = error == NULL;
643 match = var_is_str_missing (src_var, value, MV_ANY);
656 /* Performs RECODE transformation. */
658 recode_trns_proc (void *trns_, struct ccase **c, casenumber case_idx UNUSED)
660 struct recode_trns *trns = trns_;
663 *c = case_unshare (*c);
664 for (i = 0; i < trns->var_cnt; i++)
666 const struct variable *src_var = trns->src_vars[i];
667 const struct variable *dst_var = trns->dst_vars[i];
668 const struct map_out *out;
670 if (trns->src_type == VAL_NUMERIC)
671 out = find_src_numeric (trns, case_num (*c, src_var), src_var);
673 out = find_src_string (trns, case_str (*c, src_var), src_var);
675 if (trns->dst_type == VAL_NUMERIC)
677 double *dst = &case_data_rw (*c, dst_var)->f;
679 *dst = !out->copy_input ? out->value.f : case_num (*c, src_var);
680 else if (trns->src_vars != trns->dst_vars)
685 char *dst = CHAR_CAST_BUG (char *, case_str_rw (*c, dst_var));
688 if (!out->copy_input)
689 memcpy (dst, value_str (&out->value, trns->max_dst_width),
690 var_get_width (dst_var));
691 else if (trns->src_vars != trns->dst_vars)
693 union value *dst_data = case_data_rw (*c, dst_var);
694 const union value *src_data = case_data (*c, src_var);
695 value_copy_rpad (dst_data, var_get_width (dst_var),
696 src_data, var_get_width (src_var), ' ');
699 else if (trns->src_vars != trns->dst_vars)
700 memset (dst, ' ', var_get_width (dst_var));
704 return TRNS_CONTINUE;
707 /* Frees a RECODE transformation. */
709 recode_trns_free (void *trns_)
711 struct recode_trns *trns = trns_;
712 pool_destroy (trns->pool);