lexer: Use lex_is_string() more consistently.
[pspp] / src / language / xforms / recode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010 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/message.h"
38 #include "libpspp/pool.h"
39 #include "libpspp/str.h"
40
41 #include "gl/xalloc.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45 \f
46 /* Definitions. */
47
48 /* Type of source value for RECODE. */
49 enum map_in_type
50   {
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. */
57   };
58
59 /* Describes input values to be mapped. */
60 struct map_in
61   {
62     enum map_in_type type;      /* One of MAP_*. */
63     union value x, y;           /* Source values. */
64   };
65
66 /* Describes the value used as output from a mapping. */
67 struct map_out
68   {
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. */
72   };
73
74 /* Describes how to recode a single value or range of values into a
75    single value.  */
76 struct mapping
77   {
78     struct map_in in;           /* Input values. */
79     struct map_out out;         /* Output value. */
80   };
81
82 /* RECODE transformation. */
83 struct recode_trns
84   {
85     struct pool *pool;
86
87
88
89     /* Variable types, for convenience. */
90     enum val_type src_type;     /* src_vars[*] type. */
91     enum val_type dst_type;     /* dst_vars[*] type. */
92
93     /* Variables. */
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. */
99
100     /* Mappings. */
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. */
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 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                             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 == VAL_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 map_allocated;
196   bool have_dst_type;
197   size_t i;
198
199   /* Find length of longest source variable. */
200   trns->max_src_width = var_get_width (trns->src_vars[0]);
201   for (i = 1; i < trns->var_cnt; i++)
202     {
203       size_t var_width = var_get_width (trns->src_vars[i]);
204       if (var_width > trns->max_src_width)
205         trns->max_src_width = var_width;
206     }
207
208   /* Parse the mappings in parentheses. */
209   trns->mappings = NULL;
210   trns->map_cnt = 0;
211   map_allocated = 0;
212   have_dst_type = false;
213   if (!lex_force_match (lexer, '('))
214     return false;
215   do
216     {
217       enum val_type dst_type;
218
219       if (!lex_match_id (lexer, "CONVERT"))
220         {
221           struct map_out out;
222           size_t first_map_idx;
223           size_t i;
224
225           first_map_idx = trns->map_cnt;
226
227           /* Parse source specifications. */
228           do
229             {
230               struct map_in in;
231
232               if (!parse_map_in (lexer, &in, trns->pool,
233                                  trns->src_type, trns->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
243           if (out.copy_input)
244             dst_type = trns->src_type;
245           else
246             dst_type = val_type_from_width (out.width);
247           if (have_dst_type && dst_type != trns->dst_type)
248             {
249               msg (SE, _("Inconsistent target variable types.  "
250                          "Target variables "
251                          "must be all numeric or all string."));
252               return false;
253             }
254
255           for (i = first_map_idx; i < trns->map_cnt; i++)
256             trns->mappings[i].out = out;
257         }
258       else
259         {
260           /* Parse CONVERT as a special case. */
261           struct map_in in;
262           set_map_in_generic (&in, MAP_CONVERT);
263           add_mapping (trns, &map_allocated, &in);
264           set_map_out_num (&trns->mappings[trns->map_cnt - 1].out, 0.0);
265
266           dst_type = VAL_NUMERIC;
267           if (trns->src_type != VAL_STRING
268               || (have_dst_type && trns->dst_type != VAL_NUMERIC))
269             {
270               msg (SE, _("CONVERT requires string input values and "
271                          "numeric output values."));
272               return false;
273             }
274         }
275       trns->dst_type = dst_type;
276       have_dst_type = true;
277
278       if (!lex_force_match (lexer, ')'))
279         return false;
280     }
281   while (lex_match (lexer, '('));
282
283   return true;
284 }
285
286 /* Parses a mapping input value into IN, allocating memory from
287    POOL.  The source value type must be provided as SRC_TYPE and,
288    if string, the maximum width of a string source variable must
289    be provided in MAX_SRC_WIDTH.  Returns true if successful,
290    false on parse error. */
291 static bool
292 parse_map_in (struct lexer *lexer, struct map_in *in, struct pool *pool,
293               enum val_type src_type, size_t max_src_width)
294 {
295
296   if (lex_match_id (lexer, "ELSE"))
297     set_map_in_generic (in, MAP_ELSE);
298   else if (src_type == VAL_NUMERIC)
299     {
300       if (lex_match_id (lexer, "MISSING"))
301         set_map_in_generic (in, MAP_MISSING);
302       else if (lex_match_id (lexer, "SYSMIS"))
303         set_map_in_generic (in, MAP_SYSMIS);
304       else
305         {
306           double x, y;
307           if (!parse_num_range (lexer, &x, &y, NULL))
308             return false;
309           set_map_in_num (in, x == y ? MAP_SINGLE : MAP_RANGE, x, y);
310         }
311     }
312   else
313     {
314       if (lex_match_id (lexer, "MISSING"))
315         set_map_in_generic (in, MAP_MISSING);
316       else if (!lex_force_string (lexer))
317         return false;
318       else 
319         {
320           set_map_in_str (in, pool, lex_tokstr (lexer), max_src_width);
321           lex_get (lexer);
322           if (lex_token (lexer) == T_ID
323               && lex_id_match (ss_cstr ("THRU"), ss_cstr (lex_tokid (lexer))))
324             {
325               msg (SE, _("THRU is not allowed with string variables."));
326               return false;
327             }
328         }
329     }
330
331   return true;
332 }
333
334 /* Adds IN to the list of mappings in TRNS.
335    MAP_ALLOCATED is the current number of allocated mappings,
336    which is updated as needed. */
337 static void
338 add_mapping (struct recode_trns *trns,
339              size_t *map_allocated, const struct map_in *in)
340 {
341   struct mapping *m;
342   if (trns->map_cnt >= *map_allocated)
343     trns->mappings = pool_2nrealloc (trns->pool, trns->mappings,
344                                      map_allocated,
345                                      sizeof *trns->mappings);
346   m = &trns->mappings[trns->map_cnt++];
347   m->in = *in;
348 }
349
350 /* Sets IN as a mapping of the given TYPE. */
351 static void
352 set_map_in_generic (struct map_in *in, enum map_in_type type)
353 {
354   in->type = type;
355 }
356
357 /* Sets IN as a numeric mapping of the given TYPE,
358    with X and Y as the two numeric values. */
359 static void
360 set_map_in_num (struct map_in *in, enum map_in_type type, double x, double y)
361 {
362   in->type = type;
363   in->x.f = x;
364   in->y.f = y;
365 }
366
367 /* Sets IN as a string mapping, with STRING as the string,
368    allocated from POOL.  The string is padded with spaces on the
369    right to WIDTH characters long. */
370 static void
371 set_map_in_str (struct map_in *in, struct pool *pool,
372                 const struct string *string, size_t width)
373 {
374   in->type = MAP_SINGLE;
375   value_init_pool (pool, &in->x, width);
376   value_copy_buf_rpad (&in->x, width,
377                        CHAR_CAST_BUG (uint8_t *, ds_data (string)),
378                        ds_length (string), ' ');
379 }
380
381 /* Parses a mapping output value into OUT, allocating memory from
382    POOL.  Returns true if successful, false on parse error. */
383 static bool
384 parse_map_out (struct lexer *lexer, struct pool *pool, struct map_out *out)
385 {
386   if (lex_is_number (lexer))
387     {
388       set_map_out_num (out, lex_number (lexer));
389       lex_get (lexer);
390     }
391   else if (lex_match_id (lexer, "SYSMIS"))
392     set_map_out_num (out, SYSMIS);
393   else if (lex_is_string (lexer))
394     {
395       set_map_out_str (out, pool, lex_tokstr (lexer));
396       lex_get (lexer);
397     }
398   else if (lex_match_id (lexer, "COPY")) 
399     {
400       out->copy_input = true;
401       out->width = 0; 
402     }
403   else
404     {
405       lex_error (lexer, _("expecting output value"));
406       return false;
407     }
408   return true;
409 }
410
411 /* Sets OUT as a numeric mapping output with the given VALUE. */
412 static void
413 set_map_out_num (struct map_out *out, double value)
414 {
415   out->copy_input = false;
416   out->value.f = value;
417   out->width = 0;
418 }
419
420 /* Sets OUT as a string mapping output with the given VALUE. */
421 static void
422 set_map_out_str (struct map_out *out, struct pool *pool,
423                  const struct string *value)
424 {
425   const char *string = ds_data (value);
426   size_t length = ds_length (value);
427
428   if (length == 0)
429     {
430       /* A length of 0 will yield a numeric value, which is not
431          what we want. */
432       string = " ";
433       length = 1;
434     }
435
436   out->copy_input = false;
437   value_init_pool (pool, &out->value, length);
438   memcpy (value_str_rw (&out->value, length), string, length);
439   out->width = length;
440 }
441
442 /* Parses a set of target variables into TRNS->dst_vars and
443    TRNS->dst_names. */
444 static bool
445 parse_dst_vars (struct lexer *lexer, struct recode_trns *trns,
446                 const struct dictionary *dict)
447 {
448   size_t i;
449
450   if (lex_match_id (lexer, "INTO"))
451     {
452       size_t name_cnt;
453       size_t i;
454
455       if (!parse_mixed_vars_pool (lexer, dict, trns->pool,
456                                   &trns->dst_names, &name_cnt,
457                                   PV_NONE))
458         return false;
459
460       if (name_cnt != trns->var_cnt)
461         {
462           msg (SE, _("%zu variable(s) cannot be recoded into "
463                      "%zu variable(s).  Specify the same number "
464                      "of variables as source and target variables."),
465                trns->var_cnt, name_cnt);
466           return false;
467         }
468
469       trns->dst_vars = pool_nalloc (trns->pool,
470                                     trns->var_cnt, sizeof *trns->dst_vars);
471       for (i = 0; i < trns->var_cnt; i++)
472         {
473           const struct variable *v;
474           v = trns->dst_vars[i] = dict_lookup_var (dict, trns->dst_names[i]);
475           if (v == NULL && trns->dst_type == VAL_STRING)
476             {
477               msg (SE, _("There is no variable named "
478                          "%s.  (All string variables specified "
479                          "on INTO must already exist.  Use the "
480                          "STRING command to create a string "
481                          "variable.)"),
482                    trns->dst_names[i]);
483               return false;
484             }
485         }
486
487     }
488   else
489     {
490       trns->dst_vars = trns->src_vars;
491       if (trns->src_type != trns->dst_type)
492         {
493           msg (SE, _("INTO is required with %s input values "
494                      "and %s output values."),
495                trns->src_type == VAL_NUMERIC ? _("numeric") : _("string"),
496                trns->dst_type == VAL_NUMERIC ? _("numeric") : _("string"));
497           return false;
498         }
499     }
500
501   for (i = 0; i < trns->var_cnt; i++)
502     {
503       const struct variable *v = trns->dst_vars[i];
504       if (v != NULL && var_get_type (v) != trns->dst_type)
505         {
506           msg (SE, _("Type mismatch.  Cannot store %s data in "
507                      "%s variable %s."),
508                trns->dst_type == VAL_STRING ? _("string") : _("numeric"),
509                var_is_alpha (v) ? _("string") : _("numeric"),
510                var_get_name (v));
511           return false;
512         }
513     }
514
515   return true;
516 }
517
518 /* Ensures that all the output values in TRNS are as wide as the
519    widest destination variable. */
520 static void
521 enlarge_dst_widths (struct recode_trns *trns)
522 {
523   size_t i;
524
525   trns->max_dst_width = 0;
526   for (i = 0; i < trns->var_cnt; i++)
527     {
528       const struct variable *v = trns->dst_vars[i];
529       if (var_get_width (v) > trns->max_dst_width)
530         trns->max_dst_width = var_get_width (v);
531     }
532
533   for (i = 0; i < trns->map_cnt; i++)
534     {
535       struct map_out *out = &trns->mappings[i].out;
536       if (!out->copy_input)
537         value_resize_pool (trns->pool, &out->value,
538                            out->width, trns->max_dst_width);
539     }
540 }
541
542 /* Creates destination variables that don't already exist. */
543 static void
544 create_dst_vars (struct recode_trns *trns, struct dictionary *dict)
545 {
546   size_t i;
547
548   trns->dst_dict = dict;
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   struct mapping *m;
612   int width = var_get_width (src_var);
613
614   for (m = trns->mappings; m < trns->mappings + trns->map_cnt; m++)
615     {
616       const struct map_in *in = &m->in;
617       struct map_out *out = &m->out;
618       bool match;
619
620       switch (in->type)
621         {
622         case MAP_SINGLE:
623           match = !memcmp (value, value_str (&in->x, trns->max_src_width),
624                            width);
625           break;
626         case MAP_ELSE:
627           match = true;
628           break;
629         case MAP_CONVERT:
630           {
631             union value uv;
632
633             msg_disable ();
634             match = data_in (ss_buffer (CHAR_CAST_BUG (char *, value), width),
635                              LEGACY_NATIVE, FMT_F, 0, 0, 0, trns->dst_dict,
636                              &uv, 0);
637             msg_enable ();
638             out->value.f = uv.f;
639             break;
640           }
641         case MAP_MISSING:
642           match = var_is_str_missing (src_var, value, MV_ANY);
643           break;
644         default:
645           NOT_REACHED ();
646         }
647
648       if (match)
649         return out;
650     }
651
652   return NULL;
653 }
654
655 /* Performs RECODE transformation. */
656 static int
657 recode_trns_proc (void *trns_, struct ccase **c, casenumber case_idx UNUSED)
658 {
659   struct recode_trns *trns = trns_;
660   size_t i;
661
662   *c = case_unshare (*c);
663   for (i = 0; i < trns->var_cnt; i++)
664     {
665       const struct variable *src_var = trns->src_vars[i];
666       const struct variable *dst_var = trns->dst_vars[i];
667       const struct map_out *out;
668
669       if (trns->src_type == VAL_NUMERIC)
670         out = find_src_numeric (trns, case_num (*c, src_var), src_var);
671       else
672         out = find_src_string (trns, case_str (*c, src_var), src_var);
673
674       if (trns->dst_type == VAL_NUMERIC)
675         {
676           double *dst = &case_data_rw (*c, dst_var)->f;
677           if (out != NULL)
678             *dst = !out->copy_input ? out->value.f : case_num (*c, src_var);
679           else if (trns->src_vars != trns->dst_vars)
680             *dst = SYSMIS;
681         }
682       else
683         {
684           char *dst = CHAR_CAST_BUG (char *, case_str_rw (*c, dst_var));
685           if (out != NULL)
686             {
687               if (!out->copy_input)
688                 memcpy (dst, value_str (&out->value, trns->max_dst_width),
689                         var_get_width (dst_var));
690               else if (trns->src_vars != trns->dst_vars)
691                 {
692                   union value *dst_data = case_data_rw (*c, dst_var);
693                   const union value *src_data = case_data (*c, src_var);
694                   value_copy_rpad (dst_data, var_get_width (dst_var),
695                                    src_data, var_get_width (src_var), ' ');
696                 }
697             }
698           else if (trns->src_vars != trns->dst_vars)
699             memset (dst, ' ', var_get_width (dst_var));
700         }
701     }
702
703   return TRNS_CONTINUE;
704 }
705
706 /* Frees a RECODE transformation. */
707 static bool
708 recode_trns_free (void *trns_)
709 {
710   struct recode_trns *trns = trns_;
711   pool_destroy (trns->pool);
712   return true;
713 }