Add support for variable sets in the system file format.
[pspp] / src / language / commands / sys-file-info.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 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 #include <config.h>
17
18 #include <ctype.h>
19 #include <errno.h>
20 #include <float.h>
21 #include <stdlib.h>
22
23 #include "data/any-reader.h"
24 #include "data/attributes.h"
25 #include "data/casereader.h"
26 #include "data/dataset.h"
27 #include "data/dictionary.h"
28 #include "data/file-handle-def.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/value-labels.h"
32 #include "data/variable.h"
33 #include "data/varset.h"
34 #include "data/vector.h"
35 #include "language/command.h"
36 #include "language/commands/file-handle.h"
37 #include "language/lexer/lexer.h"
38 #include "language/lexer/macro.h"
39 #include "language/lexer/variable-parser.h"
40 #include "libpspp/array.h"
41 #include "libpspp/hash-functions.h"
42 #include "libpspp/i18n.h"
43 #include "libpspp/message.h"
44 #include "libpspp/misc.h"
45 #include "libpspp/pool.h"
46 #include "libpspp/string-array.h"
47 #include "output/pivot-table.h"
48 #include "output/output-item.h"
49
50 #include "gl/count-one-bits.h"
51 #include "gl/localcharset.h"
52 #include "gl/intprops.h"
53 #include "gl/minmax.h"
54 #include "gl/xalloc.h"
55
56 #include "gettext.h"
57 #define _(msgid) gettext (msgid)
58 #define N_(msgid) (msgid)
59
60 /* Information to include in displaying a dictionary. */
61 enum
62   {
63     /* Variable table. */
64     DF_NAME              = 1 << 0,
65     DF_POSITION          = 1 << 1,
66     DF_LABEL             = 1 << 2,
67     DF_MEASUREMENT_LEVEL = 1 << 3,
68     DF_ROLE              = 1 << 4,
69     DF_WIDTH             = 1 << 5,
70     DF_ALIGNMENT         = 1 << 6,
71     DF_PRINT_FORMAT      = 1 << 7,
72     DF_WRITE_FORMAT      = 1 << 8,
73     DF_MISSING_VALUES    = 1 << 9,
74 #define DF_ALL_VARIABLE ((1 << 10) - 1)
75
76     /* Value labels table. */
77     DF_VALUE_LABELS      = 1 << 10,
78
79     /* Attribute table. */
80     DF_AT_ATTRIBUTES     = 1 << 11, /* Attributes whose names begin with @. */
81     DF_ATTRIBUTES        = 1 << 12, /* All other attributes. */
82   };
83
84 static void display_variables (const struct variable **, size_t, int flags);
85 static void display_value_labels (const struct variable **, size_t);
86 static void display_attributes (const struct attrset *,
87                                 const struct variable **, size_t, int flags);
88
89 static void report_encodings (const struct file_handle *, struct pool *,
90                               char **titles, bool *ids,
91                               char **strings, size_t n_strings);
92
93 static char *get_documents_as_string (const struct dictionary *);
94
95 static void
96 add_row (struct pivot_table *table, const char *attribute,
97          struct pivot_value *value)
98 {
99   int row = pivot_category_create_leaf (table->dimensions[0]->root,
100                                         pivot_value_new_text (attribute));
101   if (value)
102     pivot_table_put1 (table, row, value);
103 }
104
105 /* SYSFILE INFO utility. */
106 int
107 cmd_sysfile_info (struct lexer *lexer, struct dataset *ds)
108 {
109   struct any_reader *any_reader;
110   struct file_handle *h;
111   struct dictionary *d;
112   struct casereader *reader;
113   struct any_read_info info;
114   char *encoding;
115
116   h = NULL;
117   encoding = NULL;
118   for (;;)
119     {
120       lex_match (lexer, T_SLASH);
121
122       if (lex_match_id (lexer, "FILE") || lex_is_string (lexer))
123         {
124           lex_match (lexer, T_EQUALS);
125
126           fh_unref (h);
127           h = fh_parse (lexer, FH_REF_FILE, NULL);
128           if (h == NULL)
129             goto error;
130         }
131       else if (lex_match_id (lexer, "ENCODING"))
132         {
133           lex_match (lexer, T_EQUALS);
134
135           if (!lex_force_string (lexer))
136             goto error;
137
138           free (encoding);
139           encoding = ss_xstrdup (lex_tokss (lexer));
140
141           lex_get (lexer);
142         }
143       else
144         break;
145     }
146
147   if (h == NULL)
148     {
149       lex_sbc_missing (lexer, "FILE");
150       goto error;
151     }
152
153   any_reader = any_reader_open (h);
154   if (!any_reader)
155     {
156       free (encoding);
157       return CMD_FAILURE;
158     }
159
160   if (encoding && !strcasecmp (encoding, "detect"))
161     {
162       char **titles, **strings;
163       struct pool *pool;
164       size_t n_strings;
165       bool *ids;
166
167       pool = pool_create ();
168       n_strings = any_reader_get_strings (any_reader, pool,
169                                           &titles, &ids, &strings);
170       any_reader_close (any_reader);
171
172       report_encodings (h, pool, titles, ids, strings, n_strings);
173       fh_unref (h);
174       pool_destroy (pool);
175       free (encoding);
176
177       return CMD_SUCCESS;
178     }
179
180   reader = any_reader_decode (any_reader, encoding, &d, &info);
181   if (!reader)
182     goto error;
183   casereader_destroy (reader);
184
185   struct pivot_table *table = pivot_table_create (N_("File Information"));
186   pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Attribute"));
187
188   add_row (table, N_("File"),
189            pivot_value_new_user_text (fh_get_file_name (h), -1));
190
191   const char *label = dict_get_label (d);
192   add_row (table, N_("Label"),
193            label ? pivot_value_new_user_text (label, -1) : NULL);
194
195   add_row (table, N_("Created"),
196            pivot_value_new_user_text_nocopy (
197              xasprintf ("%s %s by %s", info.creation_date,
198                         info.creation_time, info.product)));
199
200   if (info.product_ext)
201     add_row (table, N_("Product"),
202              pivot_value_new_user_text (info.product_ext, -1));
203
204   add_row (table, N_("Integer Format"),
205            pivot_value_new_text (
206              info.integer_format == INTEGER_MSB_FIRST ? N_("Big Endian")
207              : info.integer_format == INTEGER_LSB_FIRST ? N_("Little Endian")
208              : N_("Unknown")));
209
210   add_row (table, N_("Real Format"),
211            pivot_value_new_text (
212              info.float_format == FLOAT_IEEE_DOUBLE_LE ? N_("IEEE 754 LE.")
213              : info.float_format == FLOAT_IEEE_DOUBLE_BE ? N_("IEEE 754 BE.")
214              : info.float_format == FLOAT_VAX_D ? N_("VAX D.")
215              : info.float_format == FLOAT_VAX_G ? N_("VAX G.")
216              : info.float_format == FLOAT_Z_LONG ? N_("IBM 390 Hex Long.")
217              : N_("Unknown")));
218
219   add_row (table, N_("Variables"),
220            pivot_value_new_integer (dict_get_n_vars (d)));
221
222   add_row (table, N_("Cases"),
223            (info.n_cases == -1
224             ? pivot_value_new_text (N_("Unknown"))
225             : pivot_value_new_integer (info.n_cases)));
226
227   add_row (table, N_("Type"),
228            pivot_value_new_text (info.klass->name));
229
230   struct variable *weight_var = dict_get_weight (d);
231   add_row (table, N_("Weight"),
232            (weight_var
233             ? pivot_value_new_variable (weight_var)
234             : pivot_value_new_text (N_("Not weighted"))));
235
236   add_row (table, N_("Compression"),
237            (info.compression == ANY_COMP_NONE
238             ? pivot_value_new_text (N_("None"))
239             : pivot_value_new_user_text (
240               info.compression == ANY_COMP_SIMPLE ? "SAV" : "ZSAV", -1)));
241
242   add_row (table, N_("Encoding"),
243            pivot_value_new_user_text (dict_get_encoding (d), -1));
244
245   if (dict_get_document_n_lines (d) > 0)
246     add_row (table, N_("Documents"),
247              pivot_value_new_user_text_nocopy (get_documents_as_string (d)));
248
249   pivot_table_submit (table);
250
251   size_t n_vars = dict_get_n_vars (d);
252   const struct variable **vars = xnmalloc (n_vars, sizeof *vars);
253   for (size_t i = 0; i < dict_get_n_vars (d); i++)
254     vars[i] = dict_get_var (d, i);
255   display_variables (vars, n_vars, DF_ALL_VARIABLE);
256   display_value_labels (vars, n_vars);
257   display_attributes (dict_get_attributes (dataset_dict (ds)),
258                       vars, n_vars, DF_ATTRIBUTES);
259   free (vars);
260
261   dict_unref (d);
262
263   fh_unref (h);
264   free (encoding);
265   any_read_info_destroy (&info);
266   return CMD_SUCCESS;
267
268 error:
269   fh_unref (h);
270   free (encoding);
271   return CMD_FAILURE;
272 }
273 \f
274 /* DISPLAY utility. */
275
276 static void display_documents (const struct dictionary *dict);
277 static void display_vectors (const struct dictionary *dict, int sorted);
278
279 int
280 cmd_display (struct lexer *lexer, struct dataset *ds)
281 {
282   /* Variables to display. */
283   size_t n;
284   const struct variable **vl;
285
286   if (lex_match_id (lexer, "DOCUMENTS"))
287     display_documents (dataset_dict (ds));
288   else if (lex_match_id (lexer, "FILE"))
289     {
290       if (!lex_force_match_id (lexer, "LABEL"))
291         return CMD_FAILURE;
292
293       const char *label = dict_get_label (dataset_dict (ds));
294
295       struct pivot_table *table = pivot_table_create (N_("File Label"));
296       pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Label"),
297                               N_("Label"));
298       pivot_table_put1 (table, 0,
299                         (label ? pivot_value_new_user_text (label, -1)
300                          : pivot_value_new_text (N_("(none)"))));
301       pivot_table_submit (table);
302     }
303   else
304     {
305       int flags;
306
307       bool sorted = lex_match_id (lexer, "SORTED");
308
309       if (lex_match_id (lexer, "VECTORS"))
310         {
311           display_vectors (dataset_dict(ds), sorted);
312           return CMD_SUCCESS;
313         }
314       else if (lex_match_id (lexer, "SCRATCH"))
315         {
316           dict_get_vars (dataset_dict (ds), &vl, &n, DC_ORDINARY);
317           flags = DF_NAME;
318         }
319       else
320         {
321           struct subcommand
322             {
323               const char *name;
324               int flags;
325             };
326           static const struct subcommand subcommands[] =
327             {
328               {"@ATTRIBUTES", DF_ATTRIBUTES | DF_AT_ATTRIBUTES},
329               {"ATTRIBUTES", DF_ATTRIBUTES},
330               {"DICTIONARY", (DF_NAME | DF_POSITION | DF_LABEL
331                               | DF_MEASUREMENT_LEVEL | DF_ROLE | DF_WIDTH
332                               | DF_ALIGNMENT | DF_PRINT_FORMAT
333                               | DF_WRITE_FORMAT | DF_MISSING_VALUES
334                               | DF_VALUE_LABELS)},
335               {"INDEX", DF_NAME | DF_POSITION},
336               {"LABELS", DF_NAME | DF_POSITION | DF_LABEL},
337               {"NAMES", DF_NAME},
338               {"VARIABLES", (DF_NAME | DF_POSITION | DF_PRINT_FORMAT
339                              | DF_WRITE_FORMAT | DF_MISSING_VALUES)},
340               {NULL, 0},
341             };
342           const struct subcommand *sbc;
343           struct dictionary *dict = dataset_dict (ds);
344
345           flags = 0;
346           for (sbc = subcommands; sbc->name != NULL; sbc++)
347             if (lex_match_id (lexer, sbc->name))
348               {
349                 flags = sbc->flags;
350                 break;
351               }
352
353           lex_match (lexer, T_SLASH);
354           lex_match_id (lexer, "VARIABLES");
355           lex_match (lexer, T_EQUALS);
356
357           if (lex_token (lexer) != T_ENDCMD)
358             {
359               if (!parse_variables_const (lexer, dict, &vl, &n, PV_NONE))
360                 {
361                   free (vl);
362                   return CMD_FAILURE;
363                 }
364             }
365           else
366             dict_get_vars (dict, &vl, &n, 0);
367         }
368
369       if (n > 0)
370         {
371           sort (vl, n, sizeof *vl, (sorted
372                                     ? compare_var_ptrs_by_name
373                                     : compare_var_ptrs_by_dict_index), NULL);
374
375           int variable_flags = flags & DF_ALL_VARIABLE;
376           if (variable_flags)
377             display_variables (vl, n, variable_flags);
378
379           if (flags & DF_VALUE_LABELS)
380             display_value_labels (vl, n);
381
382           int attribute_flags = flags & (DF_ATTRIBUTES | DF_AT_ATTRIBUTES);
383           if (attribute_flags)
384             display_attributes (dict_get_attributes (dataset_dict (ds)),
385                                 vl, n, attribute_flags);
386         }
387       else
388         msg (SN, _("No variables to display."));
389
390       free (vl);
391     }
392
393   return CMD_SUCCESS;
394 }
395
396 static int
397 compare_macros_by_name (const void *a_, const void *b_, const void *aux UNUSED)
398 {
399   const struct macro *const *ap = a_;
400   const struct macro *const *bp = b_;
401   const struct macro *a = *ap;
402   const struct macro *b = *bp;
403
404   return utf8_strcasecmp (a->name, b->name);
405 }
406
407 int
408 cmd_display_macros (struct lexer *lexer, struct dataset *ds UNUSED)
409 {
410   const struct macro_set *set = lex_get_macros (lexer);
411
412   if (hmap_is_empty (&set->macros))
413     {
414       msg (SN, _("No macros to display."));
415       return CMD_SUCCESS;
416     }
417
418   const struct macro **macros = xnmalloc (hmap_count (&set->macros),
419                                           sizeof *macros);
420   size_t n = 0;
421   const struct macro *m;
422   HMAP_FOR_EACH (m, struct macro, hmap_node, &set->macros)
423     macros[n++] = m;
424   assert (n == hmap_count (&set->macros));
425   sort (macros, n, sizeof *macros, compare_macros_by_name, NULL);
426
427   struct pivot_table *table = pivot_table_create (N_("Macros"));
428
429   struct pivot_dimension *attributes = pivot_dimension_create (
430     table, PIVOT_AXIS_COLUMN, N_("Attributes"));
431   pivot_category_create_leaf (attributes->root,
432                               pivot_value_new_text (N_("Source Location")));
433
434   struct pivot_dimension *names = pivot_dimension_create (
435     table, PIVOT_AXIS_ROW, N_("Name"));
436   names->root->show_label = true;
437
438   for (size_t i = 0; i < n; i++)
439     {
440       const struct macro *m = macros[i];
441
442       pivot_category_create_leaf (names->root,
443                                   pivot_value_new_user_text (m->name, -1));
444
445       struct string location = DS_EMPTY_INITIALIZER;
446       msg_location_format (m->location, &location);
447       pivot_table_put2 (
448         table, 0, i,
449         pivot_value_new_user_text_nocopy (ds_steal_cstr (&location)));
450     }
451
452   pivot_table_submit (table);
453
454   free (macros);
455
456   return CMD_SUCCESS;
457 }
458
459 int
460 cmd_display_variable_sets (struct lexer *lexer UNUSED, struct dataset *ds)
461 {
462   const struct dictionary *dict = dataset_dict (ds);
463   size_t n_varsets = dict_get_n_varsets (dict);
464   if (n_varsets == 0)
465     {
466       msg (SN, _("No variable sets defined."));
467       return CMD_SUCCESS;
468     }
469
470   struct pivot_table *table = pivot_table_create (N_("Variable Sets"));
471   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Attributes"),
472                           N_("Variable"));
473   struct pivot_dimension *varset_dim = pivot_dimension_create (
474     table, PIVOT_AXIS_ROW, N_("Variable Set and Position"));
475   varset_dim->root->show_label = true;
476
477   for (size_t i = 0; i < n_varsets; i++)
478     {
479       const struct varset *vs = dict_get_varset (dict, i);
480
481       struct pivot_category *group = pivot_category_create_group__ (
482         varset_dim->root, pivot_value_new_user_text (
483           vs->name, -1));
484
485       for (size_t j = 0; j < vs->n_vars; j++)
486         {
487           struct variable *var = vs->vars[j];
488
489           int row = pivot_category_create_leaf (
490             group, pivot_value_new_integer (j + 1));
491
492           pivot_table_put2 (table, 0, row, pivot_value_new_variable (var));
493         }
494
495       if (!vs->n_vars)
496         {
497           int row = pivot_category_create_leaf (
498             group, pivot_value_new_user_text ("n/a", -1));
499
500           pivot_table_put2 (table, 0, row,
501                             pivot_value_new_text (N_("(empty)")));
502         }
503     }
504
505   pivot_table_submit (table);
506
507   return CMD_SUCCESS;
508 }
509
510 static char *
511 get_documents_as_string (const struct dictionary *dict)
512 {
513   const struct string_array *documents = dict_get_documents (dict);
514   struct string s = DS_EMPTY_INITIALIZER;
515   for (size_t i = 0; i < documents->n; i++)
516     {
517       if (i)
518         ds_put_byte (&s, '\n');
519       ds_put_cstr (&s, documents->strings[i]);
520     }
521   return ds_steal_cstr (&s);
522 }
523
524 static void
525 display_documents (const struct dictionary *dict)
526 {
527   struct pivot_table *table = pivot_table_create (N_("Documents"));
528   struct pivot_dimension *d = pivot_dimension_create (
529     table, PIVOT_AXIS_COLUMN, N_("Documents"), N_("Document"));
530   d->hide_all_labels = true;
531
532   if (!dict_get_documents (dict)->n)
533     pivot_table_put1 (table, 0, pivot_value_new_text (N_("(none)")));
534   else
535     {
536       char *docs = get_documents_as_string (dict);
537       pivot_table_put1 (table, 0, pivot_value_new_user_text_nocopy (docs));
538     }
539
540   pivot_table_submit (table);
541 }
542
543 static void
544 display_variables (const struct variable **vl, size_t n, int flags)
545 {
546   struct pivot_table *table = pivot_table_create (N_("Variables"));
547
548   struct pivot_dimension *attributes = pivot_dimension_create (
549     table, PIVOT_AXIS_COLUMN, N_("Attributes"));
550
551   struct heading
552     {
553       int flag;
554       const char *title;
555     };
556   static const struct heading headings[] = {
557     { DF_POSITION, N_("Position") },
558     { DF_LABEL, N_("Label") },
559     { DF_MEASUREMENT_LEVEL, N_("Measurement Level") },
560     { DF_ROLE, N_("Role") },
561     { DF_WIDTH, N_("Width") },
562     { DF_ALIGNMENT, N_("Alignment") },
563     { DF_PRINT_FORMAT, N_("Print Format") },
564     { DF_WRITE_FORMAT, N_("Write Format") },
565     { DF_MISSING_VALUES, N_("Missing Values") },
566   };
567   for (size_t i = 0; i < sizeof headings / sizeof *headings; i++)
568     if (flags & headings[i].flag)
569       pivot_category_create_leaf (attributes->root,
570                                   pivot_value_new_text (headings[i].title));
571
572   struct pivot_dimension *names = pivot_dimension_create (
573     table, PIVOT_AXIS_ROW, N_("Name"));
574   names->root->show_label = true;
575
576   for (size_t i = 0; i < n; i++)
577     {
578       const struct variable *v = vl[i];
579
580       struct pivot_value *name = pivot_value_new_variable (v);
581       name->variable.show = SETTINGS_VALUE_SHOW_VALUE;
582       int row = pivot_category_create_leaf (names->root, name);
583
584       int x = 0;
585       if (flags & DF_POSITION)
586         pivot_table_put2 (table, x++, row, pivot_value_new_integer (
587                             var_get_dict_index (v) + 1));
588
589       if (flags & DF_LABEL)
590         {
591           const char *label = var_get_label (v);
592           if (label)
593             pivot_table_put2 (table, x, row,
594                               pivot_value_new_user_text (label, -1));
595           x++;
596         }
597
598       if (flags & DF_MEASUREMENT_LEVEL)
599         pivot_table_put2 (
600           table, x++, row,
601           pivot_value_new_text (measure_to_string (var_get_measure (v))));
602
603       if (flags & DF_ROLE)
604         pivot_table_put2 (
605           table, x++, row,
606           pivot_value_new_text (var_role_to_string (var_get_role (v))));
607
608       if (flags & DF_WIDTH)
609         pivot_table_put2 (
610           table, x++, row,
611           pivot_value_new_integer (var_get_display_width (v)));
612
613       if (flags & DF_ALIGNMENT)
614         pivot_table_put2 (
615           table, x++, row,
616           pivot_value_new_text (alignment_to_string (
617                                   var_get_alignment (v))));
618
619       if (flags & DF_PRINT_FORMAT)
620         {
621           struct fmt_spec print = var_get_print_format (v);
622           char s[FMT_STRING_LEN_MAX + 1];
623
624           pivot_table_put2 (
625             table, x++, row,
626             pivot_value_new_user_text (fmt_to_string (print, s), -1));
627         }
628
629       if (flags & DF_WRITE_FORMAT)
630         {
631           struct fmt_spec write = var_get_write_format (v);
632           char s[FMT_STRING_LEN_MAX + 1];
633
634           pivot_table_put2 (
635             table, x++, row,
636             pivot_value_new_user_text (fmt_to_string (write, s), -1));
637         }
638
639       if (flags & DF_MISSING_VALUES)
640         {
641           char *s = mv_to_string (var_get_missing_values (v),
642                                   var_get_encoding (v));
643           if (s)
644             pivot_table_put2 (
645               table, x, row,
646               pivot_value_new_user_text_nocopy (s));
647
648           x++;
649         }
650     }
651
652   pivot_table_submit (table);
653 }
654
655 static bool
656 any_value_labels (const struct variable **vars, size_t n_vars)
657 {
658   for (size_t i = 0; i < n_vars; i++)
659     if (val_labs_count (var_get_value_labels (vars[i])))
660       return true;
661   return false;
662 }
663
664 static void
665 display_value_labels (const struct variable **vars, size_t n_vars)
666 {
667   if (!any_value_labels (vars, n_vars))
668     return;
669
670   struct pivot_table *table = pivot_table_create (N_("Value Labels"));
671
672   pivot_dimension_create (table, PIVOT_AXIS_COLUMN,
673                           N_("Label"), N_("Label"));
674
675   struct pivot_dimension *values = pivot_dimension_create (
676     table, PIVOT_AXIS_ROW, N_("Variable Value"));
677   values->root->show_label = true;
678
679   struct pivot_footnote *missing_footnote = pivot_table_create_footnote (
680     table, pivot_value_new_text (N_("User-missing value")));
681
682   for (size_t i = 0; i < n_vars; i++)
683     {
684       const struct val_labs *val_labs = var_get_value_labels (vars[i]);
685       size_t n_labels = val_labs_count (val_labs);
686       if (!n_labels)
687         continue;
688
689       struct pivot_category *group = pivot_category_create_group__ (
690         values->root, pivot_value_new_variable (vars[i]));
691
692       const struct val_lab **labels = val_labs_sorted (val_labs);
693       for (size_t j = 0; j < n_labels; j++)
694         {
695           const struct val_lab *vl = labels[j];
696
697           struct pivot_value *value = pivot_value_new_var_value (
698             vars[i], &vl->value);
699           if (value->type == PIVOT_VALUE_NUMERIC)
700             value->numeric.show = SETTINGS_VALUE_SHOW_VALUE;
701           else
702             value->string.show = SETTINGS_VALUE_SHOW_VALUE;
703           if (var_is_value_missing (vars[i], &vl->value) == MV_USER)
704             pivot_value_add_footnote (value, missing_footnote);
705           int row = pivot_category_create_leaf (group, value);
706
707           struct pivot_value *label = pivot_value_new_var_value (
708             vars[i], &vl->value);
709           char *escaped_label = xstrdup (val_lab_get_escaped_label (vl));
710           if (label->type == PIVOT_VALUE_NUMERIC)
711             {
712               free (label->numeric.value_label);
713               label->numeric.value_label = escaped_label;
714               label->numeric.show = SETTINGS_VALUE_SHOW_LABEL;
715             }
716           else
717             {
718               free (label->string.value_label);
719               label->string.value_label = escaped_label;
720               label->string.show = SETTINGS_VALUE_SHOW_LABEL;
721             }
722           pivot_table_put2 (table, 0, row, label);
723         }
724       free (labels);
725     }
726   pivot_table_submit (table);
727 }
728 \f
729 static bool
730 is_at_name (const char *name)
731 {
732   return name[0] == '@' || (name[0] == '$' && name[1] == '@');
733 }
734
735 static size_t
736 count_attributes (const struct attrset *set, int flags)
737 {
738   struct attrset_iterator i;
739   struct attribute *attr;
740   size_t n_attrs;
741
742   n_attrs = 0;
743   for (attr = attrset_first (set, &i); attr != NULL;
744        attr = attrset_next (set, &i))
745     if (flags & DF_AT_ATTRIBUTES || !is_at_name (attribute_get_name (attr)))
746       n_attrs += attribute_get_n_values (attr);
747   return n_attrs;
748 }
749
750 static void
751 display_attrset (struct pivot_table *table, struct pivot_value *set_name,
752                  const struct attrset *set, int flags)
753 {
754   size_t n_total = count_attributes (set, flags);
755   if (!n_total)
756     {
757       pivot_value_destroy (set_name);
758       return;
759     }
760
761   struct pivot_category *group = pivot_category_create_group__ (
762     table->dimensions[1]->root, set_name);
763
764   size_t n_attrs = attrset_count (set);
765   struct attribute **attrs = attrset_sorted (set);
766   for (size_t i = 0; i < n_attrs; i++)
767     {
768       const struct attribute *attr = attrs[i];
769       const char *name = attribute_get_name (attr);
770
771       if (!(flags & DF_AT_ATTRIBUTES) && is_at_name (name))
772         continue;
773
774       size_t n_values = attribute_get_n_values (attr);
775       for (size_t j = 0; j < n_values; j++)
776         {
777           int row = pivot_category_create_leaf (
778             group,
779             (n_values > 1
780              ? pivot_value_new_user_text_nocopy (xasprintf (
781                                                    "%s[%zu]", name, j + 1))
782              : pivot_value_new_user_text (name, -1)));
783           pivot_table_put2 (table, 0, row,
784                             pivot_value_new_user_text (
785                               attribute_get_value (attr, j), -1));
786         }
787     }
788   free (attrs);
789 }
790
791 static void
792 display_attributes (const struct attrset *dict_attrset,
793                     const struct variable **vars, size_t n_vars, int flags)
794 {
795   struct pivot_table *table = pivot_table_create (
796     N_("Variable and Dataset Attributes"));
797
798   pivot_dimension_create (table, PIVOT_AXIS_COLUMN,
799                           N_("Value"), N_("Value"));
800
801   struct pivot_dimension *variables = pivot_dimension_create (
802     table, PIVOT_AXIS_ROW, N_("Variable and Name"));
803   variables->root->show_label = true;
804
805   display_attrset (table, pivot_value_new_text (N_("(dataset)")),
806                    dict_attrset, flags);
807   for (size_t i = 0; i < n_vars; i++)
808     display_attrset (table, pivot_value_new_variable (vars[i]),
809                      var_get_attributes (vars[i]), flags);
810
811   if (pivot_table_is_empty (table))
812     pivot_table_unref (table);
813   else
814     pivot_table_submit (table);
815 }
816
817 /* Display a list of vectors.  If SORTED is nonzero then they are
818    sorted alphabetically. */
819 static void
820 display_vectors (const struct dictionary *dict, int sorted)
821 {
822   size_t n_vectors = dict_get_n_vectors (dict);
823   if (n_vectors == 0)
824     {
825       msg (SN, _("No vectors defined."));
826       return;
827     }
828
829   const struct vector **vectors = xnmalloc (n_vectors, sizeof *vectors);
830   for (size_t i = 0; i < n_vectors; i++)
831     vectors[i] = dict_get_vector (dict, i);
832   if (sorted)
833     qsort (vectors, n_vectors, sizeof *vectors, compare_vector_ptrs_by_name);
834
835   struct pivot_table *table = pivot_table_create (N_("Vectors"));
836   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Attributes"),
837                           N_("Variable"), N_("Print Format"));
838   struct pivot_dimension *vector_dim = pivot_dimension_create (
839     table, PIVOT_AXIS_ROW, N_("Vector and Position"));
840   vector_dim->root->show_label = true;
841
842   for (size_t i = 0; i < n_vectors; i++)
843     {
844       const struct vector *vec = vectors[i];
845
846       struct pivot_category *group = pivot_category_create_group__ (
847         vector_dim->root, pivot_value_new_user_text (
848           vector_get_name (vectors[i]), -1));
849
850       for (size_t j = 0; j < vector_get_n_vars (vec); j++)
851         {
852           struct variable *var = vector_get_var (vec, j);
853
854           int row = pivot_category_create_leaf (
855             group, pivot_value_new_integer (j + 1));
856
857           pivot_table_put2 (table, 0, row, pivot_value_new_variable (var));
858           char fmt_string[FMT_STRING_LEN_MAX + 1];
859           fmt_to_string (var_get_print_format (var), fmt_string);
860           pivot_table_put2 (table, 1, row,
861                             pivot_value_new_user_text (fmt_string, -1));
862         }
863     }
864
865   pivot_table_submit (table);
866
867   free (vectors);
868 }
869 \f
870 /* Encoding analysis. */
871
872 static const char *encoding_names[] = {
873   /* These encodings are from http://encoding.spec.whatwg.org/, as retrieved
874      February 2014.  Encodings not supported by glibc and encodings relevant
875      only to HTML have been removed. */
876   "utf-8",
877   "windows-1252",
878   "iso-8859-2",
879   "iso-8859-3",
880   "iso-8859-4",
881   "iso-8859-5",
882   "iso-8859-6",
883   "iso-8859-7",
884   "iso-8859-8",
885   "iso-8859-10",
886   "iso-8859-13",
887   "iso-8859-14",
888   "iso-8859-16",
889   "macintosh",
890   "windows-874",
891   "windows-1250",
892   "windows-1251",
893   "windows-1253",
894   "windows-1254",
895   "windows-1255",
896   "windows-1256",
897   "windows-1257",
898   "windows-1258",
899   "koi8-r",
900   "koi8-u",
901   "ibm866",
902   "gb18030",
903   "big5",
904   "euc-jp",
905   "iso-2022-jp",
906   "shift_jis",
907   "euc-kr",
908
909   /* Added by user request. */
910   "ibm850",
911   "din_66003",
912 };
913 #define N_ENCODING_NAMES (sizeof encoding_names / sizeof *encoding_names)
914
915 struct encoding
916   {
917     uint64_t encodings;
918     char **utf8_strings;
919     unsigned int hash;
920   };
921
922 static char **
923 recode_strings (struct pool *pool,
924                 char **strings, bool *ids, size_t n,
925                 const char *encoding)
926 {
927   char **utf8_strings;
928   size_t i;
929
930   utf8_strings = pool_alloc (pool, n * sizeof *utf8_strings);
931   for (i = 0; i < n; i++)
932     {
933       struct substring utf8;
934       int error;
935
936       error = recode_pedantically ("UTF-8", encoding, ss_cstr (strings[i]),
937                                    pool, &utf8);
938       if (!error)
939         {
940           ss_rtrim (&utf8, ss_cstr (" "));
941           utf8.string[utf8.length] = '\0';
942
943           if (ids[i] && !id_is_plausible (utf8.string))
944             error = EINVAL;
945         }
946
947       if (error)
948         return NULL;
949
950       utf8_strings[i] = utf8.string;
951     }
952
953   return utf8_strings;
954 }
955
956 static struct encoding *
957 find_duplicate_encoding (struct encoding *encodings, size_t n_encodings,
958                          char **utf8_strings, size_t n_strings,
959                          unsigned int hash)
960 {
961   struct encoding *e;
962
963   for (e = encodings; e < &encodings[n_encodings]; e++)
964     {
965       int i;
966
967       if (e->hash != hash)
968         goto next_encoding;
969
970       for (i = 0; i < n_strings; i++)
971         if (strcmp (utf8_strings[i], e->utf8_strings[i]))
972           goto next_encoding;
973
974       return e;
975     next_encoding:;
976     }
977
978   return NULL;
979 }
980
981 static bool
982 all_equal (const struct encoding *encodings, size_t n_encodings,
983            size_t string_idx)
984 {
985   const char *s0;
986   size_t i;
987
988   s0 = encodings[0].utf8_strings[string_idx];
989   for (i = 1; i < n_encodings; i++)
990     if (strcmp (s0, encodings[i].utf8_strings[string_idx]))
991       return false;
992
993   return true;
994 }
995
996 static int
997 equal_prefix (const struct encoding *encodings, size_t n_encodings,
998               size_t string_idx)
999 {
1000   const char *s0;
1001   size_t prefix;
1002   size_t i;
1003
1004   s0 = encodings[0].utf8_strings[string_idx];
1005   prefix = strlen (s0);
1006   for (i = 1; i < n_encodings; i++)
1007     {
1008       const char *si = encodings[i].utf8_strings[string_idx];
1009       size_t j;
1010
1011       for (j = 0; j < prefix; j++)
1012         if (s0[j] != si[j])
1013           {
1014             prefix = j;
1015             if (!prefix)
1016               return 0;
1017             break;
1018           }
1019     }
1020
1021   while (prefix > 0 && s0[prefix - 1] != ' ')
1022     prefix--;
1023   return prefix;
1024 }
1025
1026 static int
1027 equal_suffix (const struct encoding *encodings, size_t n_encodings,
1028               size_t string_idx)
1029 {
1030   const char *s0;
1031   size_t s0_len;
1032   size_t suffix;
1033   size_t i;
1034
1035   s0 = encodings[0].utf8_strings[string_idx];
1036   s0_len = strlen (s0);
1037   suffix = s0_len;
1038   for (i = 1; i < n_encodings; i++)
1039     {
1040       const char *si = encodings[i].utf8_strings[string_idx];
1041       size_t si_len = strlen (si);
1042       size_t j;
1043
1044       if (si_len < suffix)
1045         suffix = si_len;
1046       for (j = 0; j < suffix; j++)
1047         if (s0[s0_len - j - 1] != si[si_len - j - 1])
1048           {
1049             suffix = j;
1050             if (!suffix)
1051               return 0;
1052             break;
1053           }
1054     }
1055
1056   while (suffix > 0 && s0[s0_len - suffix] != ' ')
1057     suffix--;
1058   return suffix;
1059 }
1060
1061 static void
1062 report_encodings (const struct file_handle *h, struct pool *pool,
1063                   char **titles, bool *ids, char **strings, size_t n_strings)
1064 {
1065   struct encoding encodings[N_ENCODING_NAMES];
1066   size_t n_encodings, n_unique_strings;
1067
1068   n_encodings = 0;
1069   for (size_t i = 0; i < N_ENCODING_NAMES; i++)
1070     {
1071       char **utf8_strings;
1072       struct encoding *e;
1073       unsigned int hash;
1074
1075       utf8_strings = recode_strings (pool, strings, ids, n_strings,
1076                                      encoding_names[i]);
1077       if (!utf8_strings)
1078         continue;
1079
1080       /* Hash utf8_strings. */
1081       hash = 0;
1082       for (size_t j = 0; j < n_strings; j++)
1083         hash = hash_string (utf8_strings[j], hash);
1084
1085       /* If there's a duplicate encoding, just mark it. */
1086       e = find_duplicate_encoding (encodings, n_encodings,
1087                                    utf8_strings, n_strings, hash);
1088       if (e)
1089         {
1090           e->encodings |= UINT64_C (1) << i;
1091           continue;
1092         }
1093
1094       e = &encodings[n_encodings++];
1095       e->encodings = UINT64_C (1) << i;
1096       e->utf8_strings = utf8_strings;
1097       e->hash = hash;
1098     }
1099   if (!n_encodings)
1100     {
1101       msg (SW, _("No valid encodings found."));
1102       return;
1103     }
1104
1105   /* Table of valid encodings. */
1106   struct pivot_table *table = pivot_table_create__ (
1107     pivot_value_new_text_format (N_("Usable encodings for %s."),
1108                                  fh_get_name (h)), "Usable Encodings");
1109   pivot_table_set_caption (
1110     table, pivot_value_new_text_format (
1111       N_("Encodings that can successfully read %s (by specifying the encoding "
1112          "name on the GET command's ENCODING subcommand).  Encodings that "
1113          "yield identical text are listed together."),
1114       fh_get_name (h)));
1115
1116   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Encodings"),
1117                           N_("Encodings"));
1118   struct pivot_dimension *number = pivot_dimension_create__ (
1119     table, PIVOT_AXIS_ROW, pivot_value_new_user_text ("#", -1));
1120   number->root->show_label = true;
1121
1122   for (size_t i = 0; i < n_encodings; i++)
1123     {
1124       struct string s = DS_EMPTY_INITIALIZER;
1125       for (size_t j = 0; j < 64; j++)
1126         if (encodings[i].encodings & (UINT64_C (1) << j))
1127           ds_put_format (&s, "%s, ", encoding_names[j]);
1128       ds_chomp (&s, ss_cstr (", "));
1129
1130       int row = pivot_category_create_leaf (number->root,
1131                                             pivot_value_new_integer (i + 1));
1132       pivot_table_put2 (
1133         table, 0, row, pivot_value_new_user_text_nocopy (ds_steal_cstr (&s)));
1134     }
1135   pivot_table_submit (table);
1136
1137   n_unique_strings = 0;
1138   for (size_t i = 0; i < n_strings; i++)
1139     if (!all_equal (encodings, n_encodings, i))
1140       n_unique_strings++;
1141   if (!n_unique_strings)
1142     return;
1143
1144   /* Table of alternative interpretations. */
1145   table = pivot_table_create__ (
1146     pivot_value_new_text_format (N_("%s Encoded Text Strings"),
1147                                  fh_get_name (h)),
1148     "Alternate Encoded Text Strings");
1149   pivot_table_set_caption (
1150     table, pivot_value_new_text (
1151       N_("Text strings in the file dictionary that the previously listed "
1152          "encodings interpret differently, along with the interpretations.")));
1153
1154   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Text"), N_("Text"));
1155
1156   number = pivot_dimension_create__ (table, PIVOT_AXIS_ROW,
1157                                      pivot_value_new_user_text ("#", -1));
1158   number->root->show_label = true;
1159   for (size_t i = 0; i < n_encodings; i++)
1160     pivot_category_create_leaf (number->root,
1161                                 pivot_value_new_integer (i + 1));
1162
1163   struct pivot_dimension *purpose = pivot_dimension_create (
1164     table, PIVOT_AXIS_ROW, N_("Purpose"));
1165   purpose->root->show_label = true;
1166
1167   for (size_t i = 0; i < n_strings; i++)
1168     if (!all_equal (encodings, n_encodings, i))
1169       {
1170         int prefix = equal_prefix (encodings, n_encodings, i);
1171         int suffix = equal_suffix (encodings, n_encodings, i);
1172
1173         int purpose_idx = pivot_category_create_leaf (
1174           purpose->root, pivot_value_new_user_text (titles[i], -1));
1175
1176         for (size_t j = 0; j < n_encodings; j++)
1177           {
1178             const char *s = encodings[j].utf8_strings[i] + prefix;
1179
1180             if (prefix || suffix)
1181               {
1182                 size_t len = strlen (s) - suffix;
1183                 struct string entry;
1184
1185                 ds_init_empty (&entry);
1186                 if (prefix)
1187                   ds_put_cstr (&entry, "...");
1188                 ds_put_substring (&entry, ss_buffer (s, len));
1189                 if (suffix)
1190                   ds_put_cstr (&entry, "...");
1191
1192                 pivot_table_put3 (table, 0, j, purpose_idx,
1193                                   pivot_value_new_user_text_nocopy (
1194                                     ds_steal_cstr (&entry)));
1195               }
1196             else
1197               pivot_table_put3 (table, 0, j, purpose_idx,
1198                                 pivot_value_new_user_text (s, -1));
1199           }
1200       }
1201
1202   pivot_table_submit (table);
1203 }