1f281221a258c6e49d3a0183ccb74c01321008fb
[pspp] / src / language / dictionary / mrsets.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 2011, 2012 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 "data/data-out.h"
20 #include "data/dataset.h"
21 #include "data/dictionary.h"
22 #include "data/mrset.h"
23 #include "data/value-labels.h"
24 #include "data/variable.h"
25 #include "language/command.h"
26 #include "language/lexer/lexer.h"
27 #include "language/lexer/variable-parser.h"
28 #include "libpspp/assertion.h"
29 #include "libpspp/hmap.h"
30 #include "libpspp/i18n.h"
31 #include "libpspp/message.h"
32 #include "libpspp/str.h"
33 #include "libpspp/stringi-map.h"
34 #include "libpspp/stringi-set.h"
35 #include "output/pivot-table.h"
36
37 #include "gl/xalloc.h"
38
39 #include "gettext.h"
40 #define N_(msgid) msgid
41 #define _(msgid) gettext (msgid)
42
43 static bool parse_group (struct lexer *, struct dictionary *, enum mrset_type);
44 static bool parse_delete (struct lexer *, struct dictionary *);
45 static bool parse_display (struct lexer *, struct dictionary *);
46
47 int
48 cmd_mrsets (struct lexer *lexer, struct dataset *ds)
49 {
50   struct dictionary *dict = dataset_dict (ds);
51
52   while (lex_match (lexer, T_SLASH))
53     {
54       bool ok;
55
56       if (lex_match_id (lexer, "MDGROUP"))
57         ok = parse_group (lexer, dict, MRSET_MD);
58       else if (lex_match_id (lexer, "MCGROUP"))
59         ok = parse_group (lexer, dict, MRSET_MC);
60       else if (lex_match_id (lexer, "DELETE"))
61         ok = parse_delete (lexer, dict);
62       else if (lex_match_id (lexer, "DISPLAY"))
63         ok = parse_display (lexer, dict);
64       else
65         {
66           ok = false;
67           lex_error (lexer, NULL);
68         }
69
70       if (!ok)
71         return CMD_FAILURE;
72     }
73
74   return CMD_SUCCESS;
75 }
76
77 static bool
78 parse_group (struct lexer *lexer, struct dictionary *dict,
79              enum mrset_type type)
80 {
81   const char *subcommand_name = type == MRSET_MD ? "MDGROUP" : "MCGROUP";
82   bool labelsource_varlabel;
83   bool has_value;
84
85   struct mrset *mrset = XZALLOC (struct mrset);
86   mrset->type = type;
87   mrset->cat_source = MRSET_VARLABELS;
88
89   labelsource_varlabel = false;
90   has_value = false;
91   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
92     {
93       if (lex_match_id (lexer, "NAME"))
94         {
95           if (!lex_force_match (lexer, T_EQUALS) || !lex_force_id (lexer))
96             goto error;
97           char *error = mrset_is_valid_name__ (lex_tokcstr (lexer),
98                                                dict_get_encoding (dict));
99           if (error)
100             {
101               lex_error (lexer, "%s", error);
102               free (error);
103               goto error;
104             }
105
106           free (mrset->name);
107           mrset->name = xstrdup (lex_tokcstr (lexer));
108           lex_get (lexer);
109         }
110       else if (lex_match_id (lexer, "VARIABLES"))
111         {
112           if (!lex_force_match (lexer, T_EQUALS))
113             goto error;
114
115           free (mrset->vars);
116           if (!parse_variables (lexer, dict, &mrset->vars, &mrset->n_vars,
117                                 PV_SAME_TYPE | PV_NO_SCRATCH))
118             goto error;
119
120           if (mrset->n_vars < 2)
121             {
122               msg (SE, _("VARIABLES specified only variable %s on %s, but "
123                          "at least two variables are required."),
124                    var_get_name (mrset->vars[0]), subcommand_name);
125               goto error;
126             }
127         }
128       else if (lex_match_id (lexer, "LABEL"))
129         {
130           if (!lex_force_match (lexer, T_EQUALS) || !lex_force_string (lexer))
131             goto error;
132
133           free (mrset->label);
134           mrset->label = ss_xstrdup (lex_tokss (lexer));
135           lex_get (lexer);
136         }
137       else if (type == MRSET_MD && lex_match_id (lexer, "LABELSOURCE"))
138         {
139           if (!lex_force_match (lexer, T_EQUALS)
140               || !lex_force_match_id (lexer, "VARLABEL"))
141             goto error;
142
143           labelsource_varlabel = true;
144         }
145       else if (type == MRSET_MD && lex_match_id (lexer, "VALUE"))
146         {
147           if (!lex_force_match (lexer, T_EQUALS))
148             goto error;
149
150           has_value = true;
151           if (lex_is_number (lexer))
152             {
153               if (!lex_is_integer (lexer))
154                 {
155                   lex_error (lexer, _("Numeric VALUE must be an integer."));
156                   goto error;
157                 }
158               value_destroy (&mrset->counted, mrset->width);
159               mrset->counted.f = lex_integer (lexer);
160               mrset->width = 0;
161             }
162           else if (lex_is_string (lexer))
163             {
164               size_t width;
165               char *s;
166
167               s = recode_string (dict_get_encoding (dict), "UTF-8",
168                                  lex_tokcstr (lexer), -1);
169               width = strlen (s);
170
171               /* Trim off trailing spaces, but don't trim the string until
172                  it's empty because a width of 0 is a numeric type. */
173               while (width > 1 && s[width - 1] == ' ')
174                 width--;
175
176               value_destroy (&mrset->counted, mrset->width);
177               value_init (&mrset->counted, width);
178               memcpy (mrset->counted.s, s, width);
179               mrset->width = width;
180
181               free (s);
182             }
183           else
184             {
185               lex_error (lexer, NULL);
186               goto error;
187             }
188           lex_get (lexer);
189         }
190       else if (type == MRSET_MD && lex_match_id (lexer, "CATEGORYLABELS"))
191         {
192           if (!lex_force_match (lexer, T_EQUALS))
193             goto error;
194
195           if (lex_match_id (lexer, "VARLABELS"))
196             mrset->cat_source = MRSET_VARLABELS;
197           else if (lex_match_id (lexer, "COUNTEDVALUES"))
198             mrset->cat_source = MRSET_COUNTEDVALUES;
199           else
200             {
201               lex_error (lexer, NULL);
202               goto error;
203             }
204         }
205       else
206         {
207           lex_error (lexer, NULL);
208           goto error;
209         }
210     }
211
212   if (mrset->name == NULL)
213     {
214       lex_spec_missing (lexer, subcommand_name, "NAME");
215       goto error;
216     }
217   else if (mrset->n_vars == 0)
218     {
219       lex_spec_missing (lexer, subcommand_name, "VARIABLES");
220       goto error;
221     }
222
223   if (type == MRSET_MD)
224     {
225       /* Check that VALUE is specified and is valid for the VARIABLES. */
226       if (!has_value)
227         {
228           lex_spec_missing (lexer, subcommand_name, "VALUE");
229           goto error;
230         }
231       else if (var_is_alpha (mrset->vars[0]))
232         {
233           if (mrset->width == 0)
234             {
235               msg (SE, _("MDGROUP subcommand for group %s specifies a string "
236                          "VALUE, but the variables specified for this group "
237                          "are numeric."),
238                    mrset->name);
239               goto error;
240             }
241           else {
242             const struct variable *shortest_var;
243             int min_width;
244             size_t i;
245
246             shortest_var = NULL;
247             min_width = INT_MAX;
248             for (i = 0; i < mrset->n_vars; i++)
249               {
250                 int width = var_get_width (mrset->vars[i]);
251                 if (width < min_width)
252                   {
253                     shortest_var = mrset->vars[i];
254                     min_width = width;
255                   }
256               }
257             if (mrset->width > min_width)
258               {
259                 msg (SE, _("VALUE string on MDGROUP subcommand for group "
260                            "%s is %d bytes long, but it must be no longer "
261                            "than the narrowest variable in the group, "
262                            "which is %s with a width of %d bytes."),
263                      mrset->name, mrset->width,
264                      var_get_name (shortest_var), min_width);
265                 goto error;
266               }
267           }
268         }
269       else
270         {
271           if (mrset->width != 0)
272             {
273               msg (SE, _("MDGROUP subcommand for group %s specifies a string "
274                          "VALUE, but the variables specified for this group "
275                          "are numeric."),
276                    mrset->name);
277               goto error;
278             }
279         }
280
281       /* Implement LABELSOURCE=VARLABEL. */
282       if (labelsource_varlabel)
283         {
284           if (mrset->cat_source != MRSET_COUNTEDVALUES)
285             msg (SW, _("MDGROUP subcommand for group %s specifies "
286                        "LABELSOURCE=VARLABEL but not "
287                        "CATEGORYLABELS=COUNTEDVALUES.  "
288                        "Ignoring LABELSOURCE."),
289                  mrset->name);
290           else if (mrset->label)
291             msg (SW, _("MDGROUP subcommand for group %s specifies both LABEL "
292                        "and LABELSOURCE, but only one of these subcommands "
293                        "may be used at a time.  Ignoring LABELSOURCE."),
294                  mrset->name);
295           else
296             {
297               size_t i;
298
299               mrset->label_from_var_label = true;
300               for (i = 0; mrset->label == NULL && i < mrset->n_vars; i++)
301                 {
302                   const char *label = var_get_label (mrset->vars[i]);
303                   if (label != NULL)
304                     {
305                       mrset->label = xstrdup (label);
306                       break;
307                     }
308                 }
309             }
310         }
311
312       /* Warn if categories cannot be distinguished in output. */
313       if (mrset->cat_source == MRSET_VARLABELS)
314         {
315           struct stringi_map seen;
316           size_t i;
317
318           stringi_map_init (&seen);
319           for (i = 0; i < mrset->n_vars; i++)
320             {
321               const struct variable *var = mrset->vars[i];
322               const char *name = var_get_name (var);
323               const char *label = var_get_label (var);
324               if (label != NULL)
325                 {
326                   const char *other_name = stringi_map_find (&seen, label);
327
328                   if (other_name == NULL)
329                     stringi_map_insert (&seen, label, name);
330                   else
331                     msg (SW, _("Variables %s and %s specified as part of "
332                                "multiple dichotomy group %s have the same "
333                                "variable label.  Categories represented by "
334                                "these variables will not be distinguishable "
335                                "in output."),
336                          other_name, name, mrset->name);
337                 }
338             }
339           stringi_map_destroy (&seen);
340         }
341       else
342         {
343           struct stringi_map seen;
344           size_t i;
345
346           stringi_map_init (&seen);
347           for (i = 0; i < mrset->n_vars; i++)
348             {
349               const struct variable *var = mrset->vars[i];
350               const char *name = var_get_name (var);
351               const struct val_labs *val_labs;
352               union value value;
353               const char *label;
354
355               value_clone (&value, &mrset->counted, mrset->width);
356               value_resize (&value, mrset->width, var_get_width (var));
357
358               val_labs = var_get_value_labels (var);
359               label = val_labs_find (val_labs, &value);
360               if (label == NULL)
361                 msg (SW, _("Variable %s specified as part of multiple "
362                            "dichotomy group %s (which has "
363                            "CATEGORYLABELS=COUNTEDVALUES) has no value label "
364                            "for its counted value.  This category will not "
365                            "be distinguishable in output."),
366                      name, mrset->name);
367               else
368                 {
369                   const char *other_name = stringi_map_find (&seen, label);
370
371                   if (other_name == NULL)
372                     stringi_map_insert (&seen, label, name);
373                   else
374                     msg (SW, _("Variables %s and %s specified as part of "
375                                "multiple dichotomy group %s (which has "
376                                "CATEGORYLABELS=COUNTEDVALUES) have the same "
377                                "value label for the group's counted "
378                                "value.  These categories will not be "
379                                "distinguishable in output."),
380                          other_name, name, mrset->name);
381                 }
382             }
383           stringi_map_destroy (&seen);
384         }
385     }
386   else                          /* MCGROUP. */
387     {
388       /* Warn if categories cannot be distinguished in output. */
389       struct category
390         {
391           struct hmap_node hmap_node;
392           union value value;
393           int width;
394           const char *label;
395           const char *var_name;
396           bool warned;
397         };
398
399       struct category *c, *next;
400       struct hmap categories;
401       size_t i;
402
403       hmap_init (&categories);
404       for (i = 0; i < mrset->n_vars; i++)
405         {
406           const struct variable *var = mrset->vars[i];
407           const char *name = var_get_name (var);
408           int width = var_get_width (var);
409           const struct val_labs *val_labs;
410           const struct val_lab *vl;
411
412           val_labs = var_get_value_labels (var);
413           for (vl = val_labs_first (val_labs); vl != NULL;
414                vl = val_labs_next (val_labs, vl))
415             {
416               const union value *value = val_lab_get_value (vl);
417               const char *label = val_lab_get_label (vl);
418               unsigned int hash = value_hash (value, width, 0);
419
420               HMAP_FOR_EACH_WITH_HASH (c, struct category, hmap_node,
421                                        hash, &categories)
422                 {
423                   if (width == c->width
424                       && value_equal (value, &c->value, width))
425                     {
426                       if (!c->warned && utf8_strcasecmp (c->label, label))
427                         {
428                           char *s = data_out (value, var_get_encoding (var),
429                                               var_get_print_format (var),
430                                               settings_get_fmt_settings ());
431                           c->warned = true;
432                           msg (SW, _("Variables specified on MCGROUP should "
433                                      "have the same categories, but %s and %s "
434                                      "(and possibly others) in multiple "
435                                      "category group %s have different "
436                                      "value labels for value %s."),
437                                c->var_name, name, mrset->name, s);
438                           free (s);
439                         }
440                       goto found;
441                     }
442                 }
443
444               c = xmalloc (sizeof *c);
445               value_clone (&c->value, value, width);
446               c->width = width;
447               c->label = label;
448               c->var_name = name;
449               c->warned = false;
450               hmap_insert (&categories, &c->hmap_node, hash);
451
452             found: ;
453             }
454         }
455
456       HMAP_FOR_EACH_SAFE (c, next, struct category, hmap_node, &categories)
457         {
458           value_destroy (&c->value, c->width);
459           hmap_delete (&categories, &c->hmap_node);
460           free (c);
461         }
462       hmap_destroy (&categories);
463     }
464
465   dict_add_mrset (dict, mrset);
466   return true;
467
468 error:
469   mrset_destroy (mrset);
470   return false;
471 }
472
473 static bool
474 parse_mrset_names (struct lexer *lexer, struct dictionary *dict,
475                    struct stringi_set *mrset_names)
476 {
477   if (!lex_force_match_id (lexer, "NAME")
478       || !lex_force_match (lexer, T_EQUALS))
479     return false;
480
481   stringi_set_init (mrset_names);
482   if (lex_match (lexer, T_LBRACK))
483     {
484       while (!lex_match (lexer, T_RBRACK))
485         {
486           if (!lex_force_id (lexer))
487             return false;
488           if (dict_lookup_mrset (dict, lex_tokcstr (lexer)) == NULL)
489             {
490               lex_error (lexer, _("No multiple response set named %s."),
491                          lex_tokcstr (lexer));
492               stringi_set_destroy (mrset_names);
493               return false;
494             }
495           stringi_set_insert (mrset_names, lex_tokcstr (lexer));
496           lex_get (lexer);
497         }
498     }
499   else if (lex_match (lexer, T_ALL))
500     {
501       size_t n_sets = dict_get_n_mrsets (dict);
502       size_t i;
503
504       for (i = 0; i < n_sets; i++)
505         stringi_set_insert (mrset_names, dict_get_mrset (dict, i)->name);
506     }
507
508   return true;
509 }
510
511 static bool
512 parse_delete (struct lexer *lexer, struct dictionary *dict)
513 {
514   const struct stringi_set_node *node;
515   struct stringi_set mrset_names;
516   const char *name;
517
518   if (!parse_mrset_names (lexer, dict, &mrset_names))
519     return false;
520
521   STRINGI_SET_FOR_EACH (name, node, &mrset_names)
522     dict_delete_mrset (dict, name);
523   stringi_set_destroy (&mrset_names);
524
525   return true;
526 }
527
528 static bool
529 parse_display (struct lexer *lexer, struct dictionary *dict)
530 {
531   struct stringi_set mrset_names_set;
532   if (!parse_mrset_names (lexer, dict, &mrset_names_set))
533     return false;
534
535   size_t n = stringi_set_count (&mrset_names_set);
536   if (n == 0)
537     {
538       if (dict_get_n_mrsets (dict) == 0)
539         msg (SN, _("The active dataset dictionary does not contain any "
540                    "multiple response sets."));
541       stringi_set_destroy (&mrset_names_set);
542       return true;
543     }
544
545   struct pivot_table *table = pivot_table_create (
546     N_("Multiple Response Sets"));
547
548   pivot_dimension_create (
549     table, PIVOT_AXIS_COLUMN, N_("Attributes"),
550     N_("Label"), N_("Encoding"), N_("Counted Value"), N_("Member Variables"));
551
552   struct pivot_dimension *mrsets = pivot_dimension_create (
553     table, PIVOT_AXIS_ROW, N_("Name"));
554   mrsets->root->show_label = true;
555
556   char **mrset_names = stringi_set_get_sorted_array (&mrset_names_set);
557   for (size_t i = 0; i < n; i++)
558     {
559       const struct mrset *mrset = dict_lookup_mrset (dict, mrset_names[i]);
560
561       int row = pivot_category_create_leaf (
562         mrsets->root, pivot_value_new_user_text (mrset->name, -1));
563
564       if (mrset->label != NULL)
565         pivot_table_put2 (table, 0, row,
566                           pivot_value_new_user_text (mrset->label, -1));
567
568       pivot_table_put2 (table, 1, row,
569                         pivot_value_new_text (mrset->type == MRSET_MD
570                                               ? _("Dichotomies")
571                                               : _("Categories")));
572
573       if (mrset->type == MRSET_MD)
574         pivot_table_put2 (table, 2, row,
575                           pivot_value_new_value (
576                             &mrset->counted, mrset->width,
577                             &F_8_0, dict_get_encoding (dict)));
578
579       /* Variable names. */
580       struct string var_names = DS_EMPTY_INITIALIZER;
581       for (size_t j = 0; j < mrset->n_vars; j++)
582         ds_put_format (&var_names, "%s\n", var_get_name (mrset->vars[j]));
583       ds_chomp_byte (&var_names, '\n');
584       pivot_table_put2 (table, 3, row,
585                         pivot_value_new_user_text_nocopy (
586                           ds_steal_cstr (&var_names)));
587     }
588   free (mrset_names);
589   stringi_set_destroy (&mrset_names_set);
590
591   pivot_table_submit (table);
592
593   return true;
594 }