AUTORECODE: Always report parse errors.
[pspp] / src / language / stats / autorecode.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2012, 2013, 2014 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 <float.h>
20 #include <stdlib.h>
21
22 #include "data/case.h"
23 #include "data/casereader.h"
24 #include "data/dataset.h"
25 #include "data/dictionary.h"
26 #include "data/transformations.h"
27 #include "data/variable.h"
28 #include "language/command.h"
29 #include "language/lexer/lexer.h"
30 #include "language/lexer/variable-parser.h"
31 #include "libpspp/array.h"
32 #include "libpspp/compiler.h"
33 #include "libpspp/hash-functions.h"
34 #include "libpspp/hmap.h"
35 #include "libpspp/i18n.h"
36 #include "libpspp/message.h"
37 #include "libpspp/pool.h"
38 #include "libpspp/str.h"
39
40 #include "gl/xalloc.h"
41 #include "gl/c-xvasprintf.h"
42 #include "gl/mbiter.h"
43
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 /* FIXME: Implement PRINT subcommand. */
49
50 /* Explains how to recode one value. */
51 struct arc_item
52   {
53     struct hmap_node hmap_node; /* Element in "struct arc_spec" hash table. */
54     union value from;           /* Original value. */
55     int width;                  /* Width of the original value */
56
57     double to;                  /* Recoded value. */
58   };
59
60 /* Explains how to recode an AUTORECODE variable. */
61 struct arc_spec
62   {
63     int width;                  /* Variable width. */
64     int src_idx;                /* Case index of source variable. */
65     struct variable *dst;       /* Target variable. */
66     struct rec_items *items;
67   };
68
69 /* Descending or ascending sort order. */
70 enum arc_direction
71   {
72     ASCENDING,
73     DESCENDING
74   };
75
76 struct rec_items
77 {
78   struct hmap ht;         /* Hash table of "struct arc_item"s. */
79   int refcnt;
80 };
81
82
83
84 /* AUTORECODE data. */
85 struct autorecode_pgm
86 {
87   struct arc_spec *specs;
88   size_t n_specs;
89
90   /* Hash table of "struct arc_item"s. */
91   struct rec_items *global_items;
92
93   bool blank_valid;
94 };
95
96 static trns_proc_func autorecode_trns_proc;
97 static trns_free_func autorecode_trns_free;
98
99 static int compare_arc_items (const void *, const void *, const void *aux);
100 static void arc_free (struct autorecode_pgm *);
101 static struct arc_item *find_arc_item (const struct arc_spec *, const union value *,
102                                        size_t hash);
103
104 static bool
105 value_is_blank (const union value *val, int width, const struct dictionary *dict)
106 {
107   mbi_iterator_t iter;
108   const char *str = CHAR_CAST_BUG (const char*, value_str (val, width));
109   char *text = recode_string (UTF8, dict_get_encoding (dict), str, width);
110
111   for (mbi_init (iter, text, width); mbi_avail (iter); mbi_advance (iter))
112     {
113       mbchar_t c = mbi_cur (iter);
114
115       if ( ! mb_isblank (c))
116         {
117           free (text);
118           return false;
119         }
120     }
121
122   free (text);
123   return true;
124 }
125
126 /* Performs the AUTORECODE procedure. */
127 int
128 cmd_autorecode (struct lexer *lexer, struct dataset *ds)
129 {
130   struct autorecode_pgm *arc = NULL;
131
132   struct dictionary *dict = dataset_dict (ds);
133   const struct variable **src_vars = NULL;
134   char **dst_names = NULL;
135   size_t n_srcs = 0;
136   size_t n_dsts = 0;
137
138   enum arc_direction direction = ASCENDING;
139
140   struct casereader *input;
141   struct ccase *c;
142
143   size_t i;
144   bool ok;
145
146   /* Create procedure. */
147   arc = xzalloc (sizeof *arc);
148   arc->blank_valid = true;
149
150   /* Parse variable lists. */
151   lex_match_id (lexer, "VARIABLES");
152   lex_match (lexer, T_EQUALS);
153   if (!parse_variables_const (lexer, dict, &src_vars, &n_srcs,
154                               PV_NO_DUPLICATE | PV_NO_SCRATCH))
155     goto error;
156   lex_match (lexer, T_SLASH);
157   if (!lex_force_match_id (lexer, "INTO"))
158     goto error;
159   lex_match (lexer, T_EQUALS);
160   if (!parse_DATA_LIST_vars (lexer, dict, &dst_names, &n_dsts,
161                              PV_NO_DUPLICATE))
162     goto error;
163   if (n_dsts != n_srcs)
164     {
165       msg (SE, _("Source variable count (%zu) does not match "
166                  "target variable count (%zu)."),
167            n_srcs, n_dsts);
168
169       goto error;
170     }
171   for (i = 0; i < n_dsts; i++)
172     {
173       const char *name = dst_names[i];
174
175       if (dict_lookup_var (dict, name) != NULL)
176         {
177           msg (SE, _("Target variable %s duplicates existing variable %s."),
178                name, name);
179           goto error;
180         }
181     }
182
183   /* Parse options. */
184   while (lex_match (lexer, T_SLASH))
185     {
186       if (lex_match_id (lexer, "DESCENDING"))
187         direction = DESCENDING;
188       else if (lex_match_id (lexer, "PRINT"))
189         {
190           /* Not yet implemented. */
191         }
192       else if (lex_match_id (lexer, "GROUP"))
193         {
194           arc->global_items = xmalloc (sizeof (*arc->global_items));
195           arc->global_items->refcnt = 1;
196           hmap_init (&arc->global_items->ht);
197         }
198       else if (lex_match_id (lexer, "BLANK"))
199         {
200           lex_match (lexer, T_EQUALS);
201           if (lex_match_id (lexer, "VALID"))
202             {
203               arc->blank_valid = true;
204             }
205           else if (lex_match_id (lexer, "MISSING"))
206             {
207               arc->blank_valid = false;
208             }
209           else
210             {
211               lex_error_expecting (lexer, "VALID", "MISSING");
212               goto error;
213             }
214         }
215       else
216         {
217           lex_error_expecting (lexer, "DESCENDING", "PRINT", "GROUP", "BLANK");
218           goto error;
219         }
220     }
221
222   if (lex_token (lexer) != T_ENDCMD)
223     {
224       lex_error (lexer, _("expecting end of command"));
225       goto error;
226     }
227
228   arc->specs = xmalloc (n_dsts * sizeof *arc->specs);
229   arc->n_specs = n_dsts;
230
231
232   for (i = 0; i < n_dsts; i++)
233     {
234       struct arc_spec *spec = &arc->specs[i];
235
236       spec->width = var_get_width (src_vars[i]);
237       spec->src_idx = var_get_case_index (src_vars[i]);
238
239       if (arc->global_items)
240         {
241           arc->global_items->refcnt++;
242           spec->items = arc->global_items;
243         }
244       else
245         {
246           spec->items = xzalloc (sizeof (*spec->items));
247           spec->items->refcnt = 1;
248           hmap_init (&spec->items->ht);
249         }
250     }
251
252
253   /* Execute procedure. */
254   input = proc_open (ds);
255   for (; (c = casereader_read (input)) != NULL; case_unref (c))
256     for (i = 0; i < arc->n_specs; i++)
257       {
258         struct arc_spec *spec = &arc->specs[i];
259         int width = spec->width;
260         const union value *value = case_data_idx (c, spec->src_idx);
261         size_t hash = value_hash (value, width, 0);
262         struct arc_item *item;
263
264         item = find_arc_item (spec, value, hash);
265         if ( (item == NULL)
266              &&
267              ( arc->blank_valid
268                || val_type_from_width (spec->width) == VAL_NUMERIC
269                || ! value_is_blank (value, width, dict))
270              )
271           {
272             item = xmalloc (sizeof *item);
273             item->width = width;
274             value_clone (&item->from, value, width);
275             hmap_insert (&spec->items->ht, &item->hmap_node, hash);
276           }
277       }
278   ok = casereader_destroy (input);
279   ok = proc_commit (ds) && ok;
280
281   /* Re-fetch dictionary because it might have changed (if TEMPORARY was in
282      use). */
283   dict = dataset_dict (ds);
284
285   /* Create transformation. */
286   for (i = 0; i < arc->n_specs; i++)
287     {
288       struct arc_spec *spec = &arc->specs[i];
289       struct arc_item **items;
290       struct arc_item *item;
291       size_t n_items;
292       size_t j;
293
294       /* Create destination variable. */
295       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
296
297       /* Create array of pointers to items. */
298       n_items = hmap_count (&spec->items->ht);
299       items = xmalloc (n_items * sizeof *items);
300       j = 0;
301       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
302         items[j++] = item;
303
304       assert (j == n_items);
305
306       /* Sort array by value. */
307       sort (items, n_items, sizeof *items, compare_arc_items, NULL);
308
309       /* Assign recoded values in sorted order. */
310       for (j = 0; j < n_items; j++)
311         {
312           const union value *from = &items[j]->from;
313           char *recoded_value  = NULL;
314           const int src_width = items[j]->width;
315           union value to_val;
316           size_t len;
317
318           value_init (&to_val, 0);
319
320           items[j]->to = direction == ASCENDING ? j + 1 : n_items - j;
321
322           to_val.f = items[j]->to;
323
324           /* Add value labels to the destination variable which indicate
325              the source value from whence the new value comes. */
326           if (src_width > 0)
327             {
328               const char *str = CHAR_CAST_BUG (const char*, value_str (from, src_width));
329
330               recoded_value = recode_string (UTF8, dict_get_encoding (dict),
331                                              str, src_width);
332             }
333           else
334             recoded_value = c_xasprintf ("%.*g", DBL_DIG + 1, from->f);
335
336           /* Remove trailing whitespace */
337           len = strlen (recoded_value);
338           while (len > 0 && recoded_value[len - 1] == ' ')
339             recoded_value[--len] = '\0';
340
341           var_add_value_label (spec->dst, &to_val, recoded_value);
342           value_destroy (&to_val, 0);
343           free (recoded_value);
344         }
345
346       /* Free array. */
347       free (items);
348     }
349   add_transformation (ds, autorecode_trns_proc, autorecode_trns_free, arc);
350
351   for (i = 0; i < n_dsts; i++)
352     free (dst_names[i]);
353   free (dst_names);
354   free (src_vars);
355
356   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
357
358 error:
359   for (i = 0; i < n_dsts; i++)
360     free (dst_names[i]);
361   free (dst_names);
362   free (src_vars);
363   arc_free (arc);
364   return CMD_CASCADING_FAILURE;
365 }
366
367 static void
368 arc_free (struct autorecode_pgm *arc)
369 {
370   if (arc != NULL)
371     {
372       size_t i;
373
374       for (i = 0; i < arc->n_specs; i++)
375         {
376           struct arc_spec *spec = &arc->specs[i];
377           struct arc_item *item, *next;
378
379           HMAP_FOR_EACH_SAFE (item, next, struct arc_item, hmap_node,
380                               &spec->items->ht)
381             {
382               value_destroy (&item->from, item->width);
383               hmap_delete (&spec->items->ht, &item->hmap_node);
384               free (item);
385             }
386         }
387
388       for (i = 0; i < arc->n_specs; i++)
389         {
390           struct arc_spec *spec = &arc->specs[i];
391
392           if (--spec->items->refcnt == 0)
393             {
394               hmap_destroy (&spec->items->ht);
395               free (spec->items);
396             }
397         }
398
399       if (arc->global_items && --arc->global_items->refcnt == 0)
400         {
401           hmap_destroy (&arc->global_items->ht);
402           free (arc->global_items);
403         }
404
405       free (arc->specs);
406       free (arc);
407     }
408 }
409
410 static struct arc_item *
411 find_arc_item (const struct arc_spec *spec, const union value *value,
412                size_t hash)
413 {
414   struct arc_item *item;
415
416   HMAP_FOR_EACH_WITH_HASH (item, struct arc_item, hmap_node, hash, &spec->items->ht)
417     if (value_equal (value, &item->from, spec->width))
418       return item;
419   return NULL;
420 }
421
422 static int
423 compare_arc_items (const void *a_, const void *b_, const void *aux UNUSED)
424 {
425   const struct arc_item *const *a = a_;
426   const struct arc_item *const *b = b_;
427   int width_a = (*a)->width;
428   int width_b = (*b)->width;
429
430   if ( width_a == width_b)
431     return value_compare_3way (&(*a)->from, &(*b)->from, width_a);
432
433   if ( width_a == 0 && width_b != 0)
434     return -1;
435
436   if ( width_b == 0 && width_a != 0)
437     return +1;
438
439   return buf_compare_rpad (CHAR_CAST_BUG (const char *, value_str (&(*a)->from, width_a)), width_a,
440                            CHAR_CAST_BUG (const char *, value_str (&(*b)->from, width_b)), width_b);
441 }
442
443 static int
444 autorecode_trns_proc (void *arc_, struct ccase **c,
445                       casenumber case_idx UNUSED)
446 {
447   struct autorecode_pgm *arc = arc_;
448   size_t i;
449
450   *c = case_unshare (*c);
451   for (i = 0; i < arc->n_specs; i++)
452     {
453       const struct arc_spec *spec = &arc->specs[i];
454       const union value *value = case_data_idx (*c, spec->src_idx);
455       unsigned int hash = value_hash (value, spec->width, 0);
456       const struct arc_item *item = find_arc_item (spec, value, hash);
457
458       case_data_rw (*c, spec->dst)->f = item ? item->to : SYSMIS;
459     }
460
461   return TRNS_CONTINUE;
462 }
463
464 static bool
465 autorecode_trns_free (void *arc_)
466 {
467   struct autorecode_pgm *arc = arc_;
468
469   arc_free (arc);
470   return true;
471 }