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