2dd1dfc4641108a08deb9b3e054acb7e872e53da
[pspp-builds.git] / src / data / dictionary.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007, 2009 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 "dictionary.h"
20
21 #include <stdlib.h>
22 #include <ctype.h>
23
24 #include <data/attributes.h>
25 #include <data/case.h>
26 #include <data/category.h>
27 #include <data/identifier.h>
28 #include <data/settings.h>
29 #include <data/value-labels.h>
30 #include <data/vardict.h>
31 #include <data/variable.h>
32 #include <data/vector.h>
33 #include <libpspp/array.h>
34 #include <libpspp/assertion.h>
35 #include <libpspp/compiler.h>
36 #include <libpspp/hash.h>
37 #include <libpspp/message.h>
38 #include <libpspp/misc.h>
39 #include <libpspp/pool.h>
40 #include <libpspp/str.h>
41
42 #include "intprops.h"
43 #include "minmax.h"
44 #include "xalloc.h"
45
46 #include "gettext.h"
47 #define _(msgid) gettext (msgid)
48
49 /* A dictionary. */
50 struct dictionary
51   {
52     struct variable **var;      /* Variables. */
53     size_t var_cnt, var_cap;    /* Number of variables, capacity. */
54     struct hsh_table *name_tab; /* Variable index by name. */
55     int next_value_idx;         /* Index of next `union value' to allocate. */
56     const struct variable **split;    /* SPLIT FILE vars. */
57     size_t split_cnt;           /* SPLIT FILE count. */
58     struct variable *weight;    /* WEIGHT variable. */
59     struct variable *filter;    /* FILTER variable. */
60     casenumber case_limit;      /* Current case limit (N command). */
61     char *label;                /* File label. */
62     struct string documents;    /* Documents, as a string. */
63     struct vector **vector;     /* Vectors of variables. */
64     size_t vector_cnt;          /* Number of vectors. */
65     struct attrset attributes;  /* Custom attributes. */
66
67     char *encoding;             /* Character encoding of string data */
68
69     const struct dict_callbacks *callbacks; /* Callbacks on dictionary
70                                                modification */
71     void *cb_data ;                  /* Data passed to callbacks */
72
73     void (*changed) (struct dictionary *, void *); /* Generic change callback */
74     void *changed_data;
75   };
76
77
78 void
79 dict_set_encoding (struct dictionary *d, const char *enc)
80 {
81   if (enc)
82     d->encoding = xstrdup (enc);
83 }
84
85 const char *
86 dict_get_encoding (const struct dictionary *d)
87 {
88   return d->encoding ;
89 }
90
91
92 void
93 dict_set_change_callback (struct dictionary *d,
94                           void (*changed) (struct dictionary *, void*),
95                           void *data)
96 {
97   d->changed = changed;
98   d->changed_data = data;
99 }
100
101
102 /* Print a representation of dictionary D to stdout, for
103    debugging purposes. */
104 void
105 dict_dump (const struct dictionary *d)
106 {
107   int i;
108   for (i = 0 ; i < d->var_cnt ; ++i )
109     {
110       const struct variable *v =
111         d->var[i];
112       printf ("Name: %s;\tdict_idx: %d; case_idx: %d\n",
113               var_get_name (v),
114               var_get_dict_index (v),
115               var_get_case_index (v));
116
117     }
118 }
119
120 /* Associate CALLBACKS with DICT.  Callbacks will be invoked whenever
121    the dictionary or any of the variables it contains are modified.
122    Each callback will get passed CALLBACK_DATA.
123    Any callback may be NULL, in which case it'll be ignored.
124 */
125 void
126 dict_set_callbacks (struct dictionary *dict,
127                     const struct dict_callbacks *callbacks,
128                     void *callback_data)
129 {
130   dict->callbacks = callbacks;
131   dict->cb_data = callback_data;
132 }
133
134 /* Shallow copy the callbacks from SRC to DEST */
135 void
136 dict_copy_callbacks (struct dictionary *dest,
137                      const struct dictionary *src)
138 {
139   dest->callbacks = src->callbacks;
140   dest->cb_data = src->cb_data;
141 }
142
143 /* Creates and returns a new dictionary. */
144 struct dictionary *
145 dict_create (void)
146 {
147   struct dictionary *d = xzalloc (sizeof *d);
148
149   d->name_tab = hsh_create (8, compare_vars_by_name, hash_var_by_name,
150                             NULL, NULL);
151   attrset_init (&d->attributes);
152   return d;
153 }
154
155 /* Creates and returns a (deep) copy of an existing
156    dictionary.
157
158    The new dictionary's case indexes are copied from the old
159    dictionary.  If the new dictionary won't be used to access
160    cases produced with the old dictionary, then the new
161    dictionary's case indexes should be compacted with
162    dict_compact_values to save space. */
163 struct dictionary *
164 dict_clone (const struct dictionary *s)
165 {
166   struct dictionary *d;
167   size_t i;
168
169   assert (s != NULL);
170
171   d = dict_create ();
172
173   for (i = 0; i < s->var_cnt; i++)
174     {
175       const struct vardict_info *svdi;
176       struct vardict_info dvdi;
177       struct variable *sv = s->var[i];
178       struct variable *dv = dict_clone_var_assert (d, sv, var_get_name (sv));
179       size_t i;
180
181       for (i = 0; i < var_get_short_name_cnt (sv); i++)
182         var_set_short_name (dv, i, var_get_short_name (sv, i));
183
184       svdi = var_get_vardict (sv);
185       dvdi = *svdi;
186       dvdi.dict = d;
187       var_set_vardict (dv, &dvdi);
188     }
189
190   d->next_value_idx = s->next_value_idx;
191
192   d->split_cnt = s->split_cnt;
193   if (d->split_cnt > 0)
194     {
195       d->split = xnmalloc (d->split_cnt, sizeof *d->split);
196       for (i = 0; i < d->split_cnt; i++)
197         d->split[i] = dict_lookup_var_assert (d, var_get_name (s->split[i]));
198     }
199
200   if (s->weight != NULL)
201     dict_set_weight (d, dict_lookup_var_assert (d, var_get_name (s->weight)));
202
203   if (s->filter != NULL)
204     dict_set_filter (d, dict_lookup_var_assert (d, var_get_name (s->filter)));
205
206   d->case_limit = s->case_limit;
207   dict_set_label (d, dict_get_label (s));
208   dict_set_documents (d, dict_get_documents (s));
209
210   d->vector_cnt = s->vector_cnt;
211   d->vector = xnmalloc (d->vector_cnt, sizeof *d->vector);
212   for (i = 0; i < s->vector_cnt; i++)
213     d->vector[i] = vector_clone (s->vector[i], s, d);
214
215   if ( s->encoding)
216     d->encoding = xstrdup (s->encoding);
217
218   dict_set_attributes (d, dict_get_attributes (s));
219
220   return d;
221 }
222
223 /* Clears the contents from a dictionary without destroying the
224    dictionary itself. */
225 void
226 dict_clear (struct dictionary *d)
227 {
228   /* FIXME?  Should we really clear case_limit, label, documents?
229      Others are necessarily cleared by deleting all the variables.*/
230   assert (d != NULL);
231
232   while (d->var_cnt > 0 )
233     {
234       dict_delete_var (d, d->var[d->var_cnt - 1]);
235     }
236
237   free (d->var);
238   d->var = NULL;
239   d->var_cnt = d->var_cap = 0;
240   hsh_clear (d->name_tab);
241   d->next_value_idx = 0;
242   dict_set_split_vars (d, NULL, 0);
243   dict_set_weight (d, NULL);
244   dict_set_filter (d, NULL);
245   d->case_limit = 0;
246   free (d->label);
247   d->label = NULL;
248   ds_destroy (&d->documents);
249   dict_clear_vectors (d);
250   attrset_clear (&d->attributes);
251 }
252
253 /* Destroys the aux data for every variable in D, by calling
254    var_clear_aux() for each variable. */
255 void
256 dict_clear_aux (struct dictionary *d)
257 {
258   int i;
259
260   assert (d != NULL);
261
262   for (i = 0; i < d->var_cnt; i++)
263     var_clear_aux (d->var[i]);
264 }
265
266 /* Clears a dictionary and destroys it. */
267 void
268 dict_destroy (struct dictionary *d)
269 {
270   if (d != NULL)
271     {
272       /* In general, we don't want callbacks occuring, if the dictionary
273          is being destroyed */
274       d->callbacks  = NULL ;
275
276       dict_clear (d);
277       hsh_destroy (d->name_tab);
278       attrset_destroy (&d->attributes);
279       free (d);
280     }
281 }
282
283 /* Returns the number of variables in D. */
284 size_t
285 dict_get_var_cnt (const struct dictionary *d)
286 {
287   assert (d != NULL);
288
289   return d->var_cnt;
290 }
291
292 /* Returns the variable in D with dictionary index IDX, which
293    must be between 0 and the count returned by
294    dict_get_var_cnt(), exclusive. */
295 struct variable *
296 dict_get_var (const struct dictionary *d, size_t idx)
297 {
298   assert (d != NULL);
299   assert (idx < d->var_cnt);
300
301   return d->var[idx];
302 }
303
304 /* Sets *VARS to an array of pointers to variables in D and *CNT
305    to the number of variables in *D.  All variables are returned
306    except for those, if any, in the classes indicated by EXCLUDE.
307    (There is no point in putting DC_SYSTEM in EXCLUDE as
308    dictionaries never include system variables.) */
309 void
310 dict_get_vars (const struct dictionary *d, const struct variable ***vars,
311                size_t *cnt, enum dict_class exclude)
312 {
313   dict_get_vars_mutable (d, (struct variable ***) vars, cnt, exclude);
314 }
315
316 /* Sets *VARS to an array of pointers to variables in D and *CNT
317    to the number of variables in *D.  All variables are returned
318    except for those, if any, in the classes indicated by EXCLUDE.
319    (There is no point in putting DC_SYSTEM in EXCLUDE as
320    dictionaries never include system variables.) */
321 void
322 dict_get_vars_mutable (const struct dictionary *d, struct variable ***vars,
323                        size_t *cnt, enum dict_class exclude)
324 {
325   size_t count;
326   size_t i;
327
328   assert (d != NULL);
329   assert (vars != NULL);
330   assert (cnt != NULL);
331   assert (exclude == (exclude & DC_ALL));
332
333   count = 0;
334   for (i = 0; i < d->var_cnt; i++)
335     {
336       enum dict_class class = var_get_dict_class (d->var[i]);
337       if (!(class & exclude))
338         count++;
339     }
340
341   *vars = xnmalloc (count, sizeof **vars);
342   *cnt = 0;
343   for (i = 0; i < d->var_cnt; i++)
344     {
345       enum dict_class class = var_get_dict_class (d->var[i]);
346       if (!(class & exclude))
347         (*vars)[(*cnt)++] = d->var[i];
348     }
349   assert (*cnt == count);
350 }
351
352 static struct variable *
353 add_var (struct dictionary *d, struct variable *v)
354 {
355   /* Add dictionary info to variable. */
356   struct vardict_info vdi;
357   vdi.case_index = d->next_value_idx;
358   vdi.dict_index = d->var_cnt;
359   vdi.dict = d;
360   var_set_vardict (v, &vdi);
361
362   /* Update dictionary. */
363   if (d->var_cnt >= d->var_cap)
364     {
365       d->var_cap = 8 + 2 * d->var_cap;
366       d->var = xnrealloc (d->var, d->var_cap, sizeof *d->var);
367     }
368   d->var[d->var_cnt++] = v;
369   hsh_force_insert (d->name_tab, v);
370
371   if ( d->changed ) d->changed (d, d->changed_data);
372   if ( d->callbacks &&  d->callbacks->var_added )
373     d->callbacks->var_added (d, var_get_dict_index (v), d->cb_data);
374
375   d->next_value_idx += var_get_value_cnt (v);
376
377   return v;
378 }
379
380 /* Creates and returns a new variable in D with the given NAME
381    and WIDTH.  Returns a null pointer if the given NAME would
382    duplicate that of an existing variable in the dictionary. */
383 struct variable *
384 dict_create_var (struct dictionary *d, const char *name, int width)
385 {
386   return (dict_lookup_var (d, name) == NULL
387           ? dict_create_var_assert (d, name, width)
388           : NULL);
389 }
390
391 /* Creates and returns a new variable in D with the given NAME
392    and WIDTH.  Assert-fails if the given NAME would duplicate
393    that of an existing variable in the dictionary. */
394 struct variable *
395 dict_create_var_assert (struct dictionary *d, const char *name, int width)
396 {
397   assert (dict_lookup_var (d, name) == NULL);
398   return add_var (d, var_create (name, width));
399 }
400
401 /* Creates and returns a new variable in D with name NAME, as a
402    copy of existing variable OLD_VAR, which need not be in D or
403    in any dictionary.  Returns a null pointer if the given NAME
404    would duplicate that of an existing variable in the
405    dictionary. */
406 struct variable *
407 dict_clone_var (struct dictionary *d, const struct variable *old_var,
408                 const char *name)
409 {
410   return (dict_lookup_var (d, name) == NULL
411           ? dict_clone_var_assert (d, old_var, name)
412           : NULL);
413 }
414
415 /* Creates and returns a new variable in D with name NAME, as a
416    copy of existing variable OLD_VAR, which need not be in D or
417    in any dictionary.  Assert-fails if the given NAME would
418    duplicate that of an existing variable in the dictionary. */
419 struct variable *
420 dict_clone_var_assert (struct dictionary *d, const struct variable *old_var,
421                        const char *name)
422 {
423   struct variable *new_var = var_clone (old_var);
424   assert (dict_lookup_var (d, name) == NULL);
425   var_set_name (new_var, name);
426   return add_var (d, new_var);
427 }
428
429 /* Returns the variable named NAME in D, or a null pointer if no
430    variable has that name. */
431 struct variable *
432 dict_lookup_var (const struct dictionary *d, const char *name)
433 {
434   struct variable *target ;
435   struct variable *result ;
436
437   if ( ! var_is_plausible_name (name, false))
438     return NULL;
439
440   target = var_create (name, 0);
441   result = hsh_find (d->name_tab, target);
442   var_destroy (target);
443
444   if ( result && var_has_vardict (result)) 
445   {
446       const struct vardict_info *vdi = var_get_vardict (result);
447       assert (vdi->dict == d);
448   }
449
450   return result;
451 }
452
453 /* Returns the variable named NAME in D.  Assert-fails if no
454    variable has that name. */
455 struct variable *
456 dict_lookup_var_assert (const struct dictionary *d, const char *name)
457 {
458   struct variable *v = dict_lookup_var (d, name);
459   assert (v != NULL);
460   return v;
461 }
462
463 /* Returns true if variable V is in dictionary D,
464    false otherwise. */
465 bool
466 dict_contains_var (const struct dictionary *d, const struct variable *v)
467 {
468   if (var_has_vardict (v))
469     {
470       const struct vardict_info *vdi = var_get_vardict (v);
471       return (vdi->dict_index >= 0
472               && vdi->dict_index < d->var_cnt
473               && d->var[vdi->dict_index] == v);
474     }
475   else
476     return false;
477 }
478
479 /* Compares two double pointers to variables, which should point
480    to elements of a struct dictionary's `var' member array. */
481 static int
482 compare_var_ptrs (const void *a_, const void *b_, const void *aux UNUSED)
483 {
484   struct variable *const *a = a_;
485   struct variable *const *b = b_;
486
487   return *a < *b ? -1 : *a > *b;
488 }
489
490 /* Sets the dict_index in V's vardict to DICT_INDEX. */
491 static void
492 set_var_dict_index (struct variable *v, int dict_index)
493 {
494   struct vardict_info vdi = *var_get_vardict (v);
495   struct dictionary *d = vdi.dict;
496   vdi.dict_index = dict_index;
497   var_set_vardict (v, &vdi);
498
499   if ( d->changed ) d->changed (d, d->changed_data);
500   if ( d->callbacks &&  d->callbacks->var_changed )
501     d->callbacks->var_changed (d, dict_index, d->cb_data);
502 }
503
504 /* Sets the case_index in V's vardict to CASE_INDEX. */
505 static void
506 set_var_case_index (struct variable *v, int case_index)
507 {
508   struct vardict_info vdi = *var_get_vardict (v);
509   vdi.case_index = case_index;
510   var_set_vardict (v, &vdi);
511 }
512
513 /* Re-sets the dict_index in the dictionary variables with
514    indexes from FROM to TO (exclusive). */
515 static void
516 reindex_vars (struct dictionary *d, size_t from, size_t to)
517 {
518   size_t i;
519
520   for (i = from; i < to; i++)
521     set_var_dict_index (d->var[i], i);
522 }
523
524 /* Deletes variable V from dictionary D and frees V.
525
526    This is a very bad idea if there might be any pointers to V
527    from outside D.  In general, no variable in the active file's
528    dictionary should be deleted when any transformations are
529    active on the dictionary's dataset, because those
530    transformations might reference the deleted variable.  The
531    safest time to delete a variable is just after a procedure has
532    been executed, as done by DELETE VARIABLES.
533
534    Pointers to V within D are not a problem, because
535    dict_delete_var() knows to remove V from split variables,
536    weights, filters, etc. */
537 void
538 dict_delete_var (struct dictionary *d, struct variable *v)
539 {
540   int dict_index = var_get_dict_index (v);
541   const int case_index = var_get_case_index (v);
542   const int val_cnt = var_get_value_cnt (v);
543
544   assert (dict_contains_var (d, v));
545
546   /* Delete aux data. */
547   var_clear_aux (v);
548
549   dict_unset_split_var (d, v);
550
551   if (d->weight == v)
552     dict_set_weight (d, NULL);
553
554   if (d->filter == v)
555     dict_set_filter (d, NULL);
556
557   dict_clear_vectors (d);
558
559   /* Remove V from var array. */
560   remove_element (d->var, d->var_cnt, sizeof *d->var, dict_index);
561   d->var_cnt--;
562
563   /* Update dict_index for each affected variable. */
564   reindex_vars (d, dict_index, d->var_cnt);
565
566   /* Update name hash. */
567   hsh_force_delete (d->name_tab, v);
568
569
570   /* Free memory. */
571   var_clear_vardict (v);
572   var_destroy (v);
573
574   if ( d->changed ) d->changed (d, d->changed_data);
575   if (d->callbacks &&  d->callbacks->var_deleted )
576     d->callbacks->var_deleted (d, dict_index, case_index, val_cnt, d->cb_data);
577 }
578
579 /* Deletes the COUNT variables listed in VARS from D.  This is
580    unsafe; see the comment on dict_delete_var() for details. */
581 void
582 dict_delete_vars (struct dictionary *d,
583                   struct variable *const *vars, size_t count)
584 {
585   /* FIXME: this can be done in O(count) time, but this algorithm
586      is O(count**2). */
587   assert (d != NULL);
588   assert (count == 0 || vars != NULL);
589
590   while (count-- > 0)
591     dict_delete_var (d, *vars++);
592 }
593
594 /* Deletes the COUNT variables in D starting at index IDX.  This
595    is unsafe; see the comment on dict_delete_var() for
596    details. */
597 void
598 dict_delete_consecutive_vars (struct dictionary *d, size_t idx, size_t count)
599 {
600   /* FIXME: this can be done in O(count) time, but this algorithm
601      is O(count**2). */
602   assert (idx + count <= d->var_cnt);
603
604   while (count-- > 0)
605     dict_delete_var (d, d->var[idx]);
606 }
607
608 /* Deletes scratch variables from dictionary D. */
609 void
610 dict_delete_scratch_vars (struct dictionary *d)
611 {
612   int i;
613
614   /* FIXME: this can be done in O(count) time, but this algorithm
615      is O(count**2). */
616   assert (d != NULL);
617
618   for (i = 0; i < d->var_cnt; )
619     if (var_get_dict_class (d->var[i]) == DC_SCRATCH)
620       dict_delete_var (d, d->var[i]);
621     else
622       i++;
623 }
624
625 /* Moves V to 0-based position IDX in D.  Other variables in D,
626    if any, retain their relative positions.  Runs in time linear
627    in the distance moved. */
628 void
629 dict_reorder_var (struct dictionary *d, struct variable *v, size_t new_index)
630 {
631   size_t old_index = var_get_dict_index (v);
632
633   assert (new_index < d->var_cnt);
634   move_element (d->var, d->var_cnt, sizeof *d->var, old_index, new_index);
635   reindex_vars (d, MIN (old_index, new_index), MAX (old_index, new_index) + 1);
636 }
637
638 /* Reorders the variables in D, placing the COUNT variables
639    listed in ORDER in that order at the beginning of D.  The
640    other variables in D, if any, retain their relative
641    positions. */
642 void
643 dict_reorder_vars (struct dictionary *d,
644                    struct variable *const *order, size_t count)
645 {
646   struct variable **new_var;
647   size_t i;
648
649   assert (d != NULL);
650   assert (count == 0 || order != NULL);
651   assert (count <= d->var_cnt);
652
653   new_var = xnmalloc (d->var_cnt, sizeof *new_var);
654   memcpy (new_var, order, count * sizeof *new_var);
655   for (i = 0; i < count; i++)
656     {
657       size_t index = var_get_dict_index (order[i]);
658       assert (d->var[index] == order[i]);
659       d->var[index] = NULL;
660       set_var_dict_index (order[i], i);
661     }
662   for (i = 0; i < d->var_cnt; i++)
663     if (d->var[i] != NULL)
664       {
665         assert (count < d->var_cnt);
666         new_var[count] = d->var[i];
667         set_var_dict_index (new_var[count], count);
668         count++;
669       }
670   free (d->var);
671   d->var = new_var;
672 }
673
674 /* Changes the name of variable V in dictionary D to NEW_NAME. */
675 static void
676 rename_var (struct dictionary *d, struct variable *v, const char *new_name)
677 {
678   struct vardict_info vdi;
679
680   assert (dict_contains_var (d, v));
681
682   vdi = *var_get_vardict (v);
683   var_clear_vardict (v);
684   var_set_name (v, new_name);
685   var_set_vardict (v, &vdi);
686 }
687
688 /* Changes the name of V in D to name NEW_NAME.  Assert-fails if
689    a variable named NEW_NAME is already in D, except that
690    NEW_NAME may be the same as V's existing name. */
691 void
692 dict_rename_var (struct dictionary *d, struct variable *v,
693                  const char *new_name)
694 {
695   assert (!strcasecmp (var_get_name (v), new_name)
696           || dict_lookup_var (d, new_name) == NULL);
697
698   hsh_force_delete (d->name_tab, v);
699   rename_var (d, v, new_name);
700   hsh_force_insert (d->name_tab, v);
701
702   if (settings_get_algorithm () == ENHANCED)
703     var_clear_short_names (v);
704
705   if ( d->changed ) d->changed (d, d->changed_data);
706   if ( d->callbacks &&  d->callbacks->var_changed )
707     d->callbacks->var_changed (d, var_get_dict_index (v), d->cb_data);
708 }
709
710 /* Renames COUNT variables specified in VARS to the names given
711    in NEW_NAMES within dictionary D.  If the renaming would
712    result in a duplicate variable name, returns false and stores a
713    name that would be duplicated into *ERR_NAME (if ERR_NAME is
714    non-null).  Otherwise, the renaming is successful, and true
715    is returned. */
716 bool
717 dict_rename_vars (struct dictionary *d,
718                   struct variable **vars, char **new_names, size_t count,
719                   char **err_name)
720 {
721   struct pool *pool;
722   char **old_names;
723   size_t i;
724
725   assert (count == 0 || vars != NULL);
726   assert (count == 0 || new_names != NULL);
727
728   /* Save the names of the variables to be renamed. */
729   pool = pool_create ();
730   old_names = pool_nalloc (pool, count, sizeof *old_names);
731   for (i = 0; i < count; i++)
732     old_names[i] = pool_strdup (pool, var_get_name (vars[i]));
733
734   /* Remove the variables to be renamed from the name hash,
735      and rename them. */
736   for (i = 0; i < count; i++)
737     {
738       hsh_force_delete (d->name_tab, vars[i]);
739       rename_var (d, vars[i], new_names[i]);
740     }
741
742   /* Add the renamed variables back into the name hash,
743      checking for conflicts. */
744   for (i = 0; i < count; i++)
745     if (hsh_insert (d->name_tab, vars[i]) != NULL)
746       {
747         /* There is a name conflict.
748            Back out all the name changes that have already
749            taken place, and indicate failure. */
750         size_t fail_idx = i;
751         if (err_name != NULL)
752           *err_name = new_names[i];
753
754         for (i = 0; i < fail_idx; i++)
755           hsh_force_delete (d->name_tab, vars[i]);
756
757         for (i = 0; i < count; i++)
758           {
759             rename_var (d, vars[i], old_names[i]);
760             hsh_force_insert (d->name_tab, vars[i]);
761           }
762
763         pool_destroy (pool);
764         return false;
765       }
766
767   /* Clear short names. */
768   if (settings_get_algorithm () == ENHANCED)
769     for (i = 0; i < count; i++)
770       var_clear_short_names (vars[i]);
771
772   pool_destroy (pool);
773   return true;
774 }
775
776 /* Returns true if a variable named NAME may be inserted in DICT;
777    that is, if there is not already a variable with that name in
778    DICT and if NAME is not a reserved word.  (The caller's checks
779    have already verified that NAME is otherwise acceptable as a
780    variable name.) */
781 static bool
782 var_name_is_insertable (const struct dictionary *dict, const char *name)
783 {
784   return (dict_lookup_var (dict, name) == NULL
785           && lex_id_to_token (ss_cstr (name)) == T_ID);
786 }
787
788 static bool
789 make_hinted_name (const struct dictionary *dict, const char *hint,
790                   char name[VAR_NAME_LEN + 1])
791 {
792   bool dropped = false;
793   char *cp;
794
795   for (cp = name; *hint && cp < name + VAR_NAME_LEN; hint++)
796     {
797       if (cp == name
798           ? lex_is_id1 (*hint) && *hint != '$'
799           : lex_is_idn (*hint))
800         {
801           if (dropped)
802             {
803               *cp++ = '_';
804               dropped = false;
805             }
806           if (cp < name + VAR_NAME_LEN)
807             *cp++ = *hint;
808         }
809       else if (cp > name)
810         dropped = true;
811     }
812   *cp = '\0';
813
814   if (name[0] != '\0')
815     {
816       size_t len = strlen (name);
817       unsigned long int i;
818
819       if (var_name_is_insertable (dict, name))
820         return true;
821
822       for (i = 0; i < ULONG_MAX; i++)
823         {
824           char suffix[INT_BUFSIZE_BOUND (i) + 1];
825           int ofs;
826
827           suffix[0] = '_';
828           if (!str_format_26adic (i + 1, &suffix[1], sizeof suffix - 1))
829             NOT_REACHED ();
830
831           ofs = MIN (VAR_NAME_LEN - strlen (suffix), len);
832           strcpy (&name[ofs], suffix);
833
834           if (var_name_is_insertable (dict, name))
835             return true;
836         }
837     }
838
839   return false;
840 }
841
842 static bool
843 make_numeric_name (const struct dictionary *dict, unsigned long int *num_start,
844                    char name[VAR_NAME_LEN + 1])
845 {
846   unsigned long int number;
847
848   for (number = num_start != NULL ? MAX (*num_start, 1) : 1;
849        number < ULONG_MAX;
850        number++)
851     {
852       sprintf (name, "VAR%03lu", number);
853       if (dict_lookup_var (dict, name) == NULL)
854         {
855           if (num_start != NULL)
856             *num_start = number + 1;
857           return true;
858         }
859     }
860
861   if (num_start != NULL)
862     *num_start = ULONG_MAX;
863   return false;
864 }
865
866
867 /* Attempts to devise a variable name unique within DICT.
868    Returns true if successful, in which case the new variable
869    name is stored into NAME.  Returns false if all names that can
870    be generated have already been taken.  (Returning false is
871    quite unlikely: at least ULONG_MAX unique names can be
872    generated.)
873
874    HINT, if it is non-null, is used as a suggestion that will be
875    modified for suitability as a variable name and for
876    uniqueness.
877
878    If HINT is null or entirely unsuitable, a name in the form
879    "VAR%03d" will be generated, where the smallest unused integer
880    value is used.  If NUM_START is non-null, then its value is
881    used as the minimum numeric value to check, and it is updated
882    to the next value to be checked.
883    */
884 bool
885 dict_make_unique_var_name (const struct dictionary *dict, const char *hint,
886                            unsigned long int *num_start,
887                            char name[VAR_NAME_LEN + 1])
888 {
889   return ((hint != NULL && make_hinted_name (dict, hint, name))
890           || make_numeric_name (dict, num_start, name));
891 }
892
893 /* Returns the weighting variable in dictionary D, or a null
894    pointer if the dictionary is unweighted. */
895 struct variable *
896 dict_get_weight (const struct dictionary *d)
897 {
898   assert (d != NULL);
899   assert (d->weight == NULL || dict_contains_var (d, d->weight));
900
901   return d->weight;
902 }
903
904 /* Returns the value of D's weighting variable in case C, except
905    that a negative weight is returned as 0.  Returns 1 if the
906    dictionary is unweighted.  Will warn about missing, negative,
907    or zero values if *WARN_ON_INVALID is true.  The function will
908    set *WARN_ON_INVALID to false if an invalid weight is
909    found. */
910 double
911 dict_get_case_weight (const struct dictionary *d, const struct ccase *c,
912                       bool *warn_on_invalid)
913 {
914   assert (d != NULL);
915   assert (c != NULL);
916
917   if (d->weight == NULL)
918     return 1.0;
919   else
920     {
921       double w = case_num (c, d->weight);
922       if (w < 0.0 || var_is_num_missing (d->weight, w, MV_ANY))
923         w = 0.0;
924       if ( w == 0.0 && warn_on_invalid != NULL && *warn_on_invalid ) {
925           *warn_on_invalid = false;
926           msg (SW, _("At least one case in the data file had a weight value "
927                      "that was user-missing, system-missing, zero, or "
928                      "negative.  These case(s) were ignored."));
929       }
930       return w;
931     }
932 }
933
934 /* Sets the weighting variable of D to V, or turning off
935    weighting if V is a null pointer. */
936 void
937 dict_set_weight (struct dictionary *d, struct variable *v)
938 {
939   assert (d != NULL);
940   assert (v == NULL || dict_contains_var (d, v));
941   assert (v == NULL || var_is_numeric (v));
942
943   d->weight = v;
944
945   if (d->changed) d->changed (d, d->changed_data);
946   if ( d->callbacks &&  d->callbacks->weight_changed )
947     d->callbacks->weight_changed (d,
948                                   v ? var_get_dict_index (v) : -1,
949                                   d->cb_data);
950 }
951
952 /* Returns the filter variable in dictionary D (see cmd_filter())
953    or a null pointer if the dictionary is unfiltered. */
954 struct variable *
955 dict_get_filter (const struct dictionary *d)
956 {
957   assert (d != NULL);
958   assert (d->filter == NULL || dict_contains_var (d, d->filter));
959
960   return d->filter;
961 }
962
963 /* Sets V as the filter variable for dictionary D.  Passing a
964    null pointer for V turn off filtering. */
965 void
966 dict_set_filter (struct dictionary *d, struct variable *v)
967 {
968   assert (d != NULL);
969   assert (v == NULL || dict_contains_var (d, v));
970   assert (v == NULL || var_is_numeric (v));
971
972   d->filter = v;
973
974   if (d->changed) d->changed (d, d->changed_data);
975   if ( d->callbacks && d->callbacks->filter_changed )
976     d->callbacks->filter_changed (d,
977                                   v ? var_get_dict_index (v) : -1,
978                                   d->cb_data);
979 }
980
981 /* Returns the case limit for dictionary D, or zero if the number
982    of cases is unlimited. */
983 casenumber
984 dict_get_case_limit (const struct dictionary *d)
985 {
986   assert (d != NULL);
987
988   return d->case_limit;
989 }
990
991 /* Sets CASE_LIMIT as the case limit for dictionary D.  Use
992    0 for CASE_LIMIT to indicate no limit. */
993 void
994 dict_set_case_limit (struct dictionary *d, casenumber case_limit)
995 {
996   assert (d != NULL);
997
998   d->case_limit = case_limit;
999 }
1000
1001 /* Returns the case index of the next value to be added to D.
1002    This value is the number of `union value's that need to be
1003    allocated to store a case for dictionary D. */
1004 int
1005 dict_get_next_value_idx (const struct dictionary *d)
1006 {
1007   assert (d != NULL);
1008
1009   return d->next_value_idx;
1010 }
1011
1012 /* Returns the number of bytes needed to store a case for
1013    dictionary D. */
1014 size_t
1015 dict_get_case_size (const struct dictionary *d)
1016 {
1017   assert (d != NULL);
1018
1019   return sizeof (union value) * dict_get_next_value_idx (d);
1020 }
1021
1022 /* Reassigns values in dictionary D so that fragmentation is
1023    eliminated. */
1024 void
1025 dict_compact_values (struct dictionary *d)
1026 {
1027   size_t i;
1028
1029   d->next_value_idx = 0;
1030   for (i = 0; i < d->var_cnt; i++)
1031     {
1032       struct variable *v = d->var[i];
1033       set_var_case_index (v, d->next_value_idx);
1034       d->next_value_idx += var_get_value_cnt (v);
1035     }
1036 }
1037
1038 /*
1039    Reassigns case indices for D, increasing each index above START by
1040    the value PADDING.
1041 */
1042 static void
1043 dict_pad_values (struct dictionary *d, int start, int padding)
1044 {
1045   size_t i;
1046
1047   if ( padding <= 0 ) 
1048         return;
1049
1050   for (i = 0; i < d->var_cnt; ++i)
1051     {
1052       struct variable *v = d->var[i];
1053
1054       int index = var_get_case_index (v);
1055
1056       if ( index >= start)
1057         set_var_case_index (v, index + padding);
1058     }
1059
1060   d->next_value_idx += padding;
1061 }
1062
1063
1064 /* Returns the number of values occupied by the variables in
1065    dictionary D.  All variables are considered if EXCLUDE_CLASSES
1066    is 0, or it may contain one or more of (1u << DC_ORDINARY),
1067    (1u << DC_SYSTEM), or (1u << DC_SCRATCH) to exclude the
1068    corresponding type of variable.
1069
1070    The return value may be less than the number of values in one
1071    of dictionary D's cases (as returned by
1072    dict_get_next_value_idx) even if E is 0, because there may be
1073    gaps in D's cases due to deleted variables. */
1074 size_t
1075 dict_count_values (const struct dictionary *d, unsigned int exclude_classes)
1076 {
1077   size_t i;
1078   size_t cnt;
1079
1080   assert ((exclude_classes & ~((1u << DC_ORDINARY)
1081                                | (1u << DC_SYSTEM)
1082                                | (1u << DC_SCRATCH))) == 0);
1083
1084   cnt = 0;
1085   for (i = 0; i < d->var_cnt; i++)
1086     {
1087       enum dict_class class = var_get_dict_class (d->var[i]);
1088       if (!(exclude_classes & (1u << class)))
1089         cnt += var_get_value_cnt (d->var[i]);
1090     }
1091   return cnt;
1092 }
1093 \f
1094 /* Returns the SPLIT FILE vars (see cmd_split_file()).  Call
1095    dict_get_split_cnt() to determine how many SPLIT FILE vars
1096    there are.  Returns a null pointer if and only if there are no
1097    SPLIT FILE vars. */
1098 const struct variable *const *
1099 dict_get_split_vars (const struct dictionary *d)
1100 {
1101   assert (d != NULL);
1102
1103   return d->split;
1104 }
1105
1106 /* Returns the number of SPLIT FILE vars. */
1107 size_t
1108 dict_get_split_cnt (const struct dictionary *d)
1109 {
1110   assert (d != NULL);
1111
1112   return d->split_cnt;
1113 }
1114
1115 /* Removes variable V, which must be in D, from D's set of split
1116    variables. */
1117 void
1118 dict_unset_split_var (struct dictionary *d, struct variable *v)
1119 {
1120   int orig_count;
1121
1122   assert (dict_contains_var (d, v));
1123
1124   orig_count = d->split_cnt;
1125   d->split_cnt = remove_equal (d->split, d->split_cnt, sizeof *d->split,
1126                                &v, compare_var_ptrs, NULL);
1127   if (orig_count != d->split_cnt)
1128     {
1129       if (d->changed) d->changed (d, d->changed_data);
1130       /* We changed the set of split variables so invoke the
1131          callback. */
1132       if (d->callbacks &&  d->callbacks->split_changed)
1133         d->callbacks->split_changed (d, d->cb_data);
1134     }
1135 }
1136
1137 /* Sets CNT split vars SPLIT in dictionary D. */
1138 void
1139 dict_set_split_vars (struct dictionary *d,
1140                      struct variable *const *split, size_t cnt)
1141 {
1142   assert (d != NULL);
1143   assert (cnt == 0 || split != NULL);
1144
1145   d->split_cnt = cnt;
1146   if ( cnt > 0 )
1147    {
1148     d->split = xnrealloc (d->split, cnt, sizeof *d->split) ;
1149     memcpy (d->split, split, cnt * sizeof *d->split);
1150    }
1151   else
1152    {
1153     free (d->split);
1154     d->split = NULL;
1155    }
1156
1157   if (d->changed) d->changed (d, d->changed_data);
1158   if ( d->callbacks &&  d->callbacks->split_changed )
1159     d->callbacks->split_changed (d, d->cb_data);
1160 }
1161
1162 /* Returns the file label for D, or a null pointer if D is
1163    unlabeled (see cmd_file_label()). */
1164 const char *
1165 dict_get_label (const struct dictionary *d)
1166 {
1167   assert (d != NULL);
1168
1169   return d->label;
1170 }
1171
1172 /* Sets D's file label to LABEL, truncating it to a maximum of 60
1173    characters. */
1174 void
1175 dict_set_label (struct dictionary *d, const char *label)
1176 {
1177   assert (d != NULL);
1178
1179   free (d->label);
1180   d->label = label != NULL ? xstrndup (label, 60) : NULL;
1181 }
1182
1183 /* Returns the documents for D, or a null pointer if D has no
1184    documents.  If the return value is nonnull, then the string
1185    will be an exact multiple of DOC_LINE_LENGTH bytes in length,
1186    with each segment corresponding to one line. */
1187 const char *
1188 dict_get_documents (const struct dictionary *d)
1189 {
1190   return ds_is_empty (&d->documents) ? NULL : ds_cstr (&d->documents);
1191 }
1192
1193 /* Sets the documents for D to DOCUMENTS, or removes D's
1194    documents if DOCUMENT is a null pointer.  If DOCUMENTS is
1195    nonnull, then it should be an exact multiple of
1196    DOC_LINE_LENGTH bytes in length, with each segment
1197    corresponding to one line. */
1198 void
1199 dict_set_documents (struct dictionary *d, const char *documents)
1200 {
1201   size_t remainder;
1202
1203   ds_assign_cstr (&d->documents, documents != NULL ? documents : "");
1204
1205   /* In case the caller didn't get it quite right, pad out the
1206      final line with spaces. */
1207   remainder = ds_length (&d->documents) % DOC_LINE_LENGTH;
1208   if (remainder != 0)
1209     ds_put_char_multiple (&d->documents, ' ', DOC_LINE_LENGTH - remainder);
1210 }
1211
1212 /* Drops the documents from dictionary D. */
1213 void
1214 dict_clear_documents (struct dictionary *d)
1215 {
1216   ds_clear (&d->documents);
1217 }
1218
1219 /* Appends LINE to the documents in D.  LINE will be truncated or
1220    padded on the right with spaces to make it exactly
1221    DOC_LINE_LENGTH bytes long. */
1222 void
1223 dict_add_document_line (struct dictionary *d, const char *line)
1224 {
1225   if (strlen (line) > DOC_LINE_LENGTH)
1226     {
1227       /* Note to translators: "bytes" is correct, not characters */
1228       msg (SW, _("Truncating document line to %d bytes."), DOC_LINE_LENGTH);
1229     }
1230   buf_copy_str_rpad (ds_put_uninit (&d->documents, DOC_LINE_LENGTH),
1231                      DOC_LINE_LENGTH, line);
1232 }
1233
1234 /* Returns the number of document lines in dictionary D. */
1235 size_t
1236 dict_get_document_line_cnt (const struct dictionary *d)
1237 {
1238   return ds_length (&d->documents) / DOC_LINE_LENGTH;
1239 }
1240
1241 /* Copies document line number IDX from dictionary D into
1242    LINE, trimming off any trailing white space. */
1243 void
1244 dict_get_document_line (const struct dictionary *d,
1245                         size_t idx, struct string *line)
1246 {
1247   assert (idx < dict_get_document_line_cnt (d));
1248   ds_assign_substring (line, ds_substr (&d->documents, idx * DOC_LINE_LENGTH,
1249                                         DOC_LINE_LENGTH));
1250   ds_rtrim (line, ss_cstr (CC_SPACES));
1251 }
1252
1253 /* Creates in D a vector named NAME that contains the CNT
1254    variables in VAR.  Returns true if successful, or false if a
1255    vector named NAME already exists in D. */
1256 bool
1257 dict_create_vector (struct dictionary *d,
1258                     const char *name,
1259                     struct variable **var, size_t cnt)
1260 {
1261   size_t i;
1262
1263   assert (var != NULL);
1264   assert (cnt > 0);
1265   for (i = 0; i < cnt; i++)
1266     assert (dict_contains_var (d, var[i]));
1267
1268   if (dict_lookup_vector (d, name) == NULL)
1269     {
1270       d->vector = xnrealloc (d->vector, d->vector_cnt + 1, sizeof *d->vector);
1271       d->vector[d->vector_cnt++] = vector_create (name, var, cnt);
1272       return true;
1273     }
1274   else
1275     return false;
1276 }
1277
1278 /* Creates in D a vector named NAME that contains the CNT
1279    variables in VAR.  A vector named NAME must not already exist
1280    in D. */
1281 void
1282 dict_create_vector_assert (struct dictionary *d,
1283                            const char *name,
1284                            struct variable **var, size_t cnt)
1285 {
1286   assert (dict_lookup_vector (d, name) == NULL);
1287   dict_create_vector (d, name, var, cnt);
1288 }
1289
1290 /* Returns the vector in D with index IDX, which must be less
1291    than dict_get_vector_cnt (D). */
1292 const struct vector *
1293 dict_get_vector (const struct dictionary *d, size_t idx)
1294 {
1295   assert (d != NULL);
1296   assert (idx < d->vector_cnt);
1297
1298   return d->vector[idx];
1299 }
1300
1301 /* Returns the number of vectors in D. */
1302 size_t
1303 dict_get_vector_cnt (const struct dictionary *d)
1304 {
1305   assert (d != NULL);
1306
1307   return d->vector_cnt;
1308 }
1309
1310 /* Looks up and returns the vector within D with the given
1311    NAME. */
1312 const struct vector *
1313 dict_lookup_vector (const struct dictionary *d, const char *name)
1314 {
1315   size_t i;
1316   for (i = 0; i < d->vector_cnt; i++)
1317     if (!strcasecmp (vector_get_name (d->vector[i]), name))
1318       return d->vector[i];
1319   return NULL;
1320 }
1321
1322 /* Deletes all vectors from D. */
1323 void
1324 dict_clear_vectors (struct dictionary *d)
1325 {
1326   size_t i;
1327
1328   for (i = 0; i < d->vector_cnt; i++)
1329     vector_destroy (d->vector[i]);
1330   free (d->vector);
1331
1332   d->vector = NULL;
1333   d->vector_cnt = 0;
1334 }
1335
1336 /* Returns D's attribute set.  The caller may examine or modify
1337    the attribute set, but must not destroy it.  Destroying D or
1338    calling dict_set_attributes for D will also destroy D's
1339    attribute set. */
1340 struct attrset *
1341 dict_get_attributes (const struct dictionary *d) 
1342 {
1343   return (struct attrset *) &d->attributes;
1344 }
1345
1346 /* Replaces D's attributes set by a copy of ATTRS. */
1347 void
1348 dict_set_attributes (struct dictionary *d, const struct attrset *attrs)
1349 {
1350   attrset_destroy (&d->attributes);
1351   attrset_clone (&d->attributes, attrs);
1352 }
1353
1354 /* Returns true if D has at least one attribute in its attribute
1355    set, false if D's attribute set is empty. */
1356 bool
1357 dict_has_attributes (const struct dictionary *d) 
1358 {
1359   return attrset_count (&d->attributes) > 0;
1360 }
1361
1362 /* Called from variable.c to notify the dictionary that some property of
1363    the variable has changed */
1364 void
1365 dict_var_changed (const struct variable *v)
1366 {
1367   if ( var_has_vardict (v))
1368     {
1369       const struct vardict_info *vdi = var_get_vardict (v);
1370       struct dictionary *d = vdi->dict;
1371
1372       if ( NULL == d)
1373         return;
1374
1375       if (d->changed ) d->changed (d, d->changed_data);
1376       if ( d->callbacks && d->callbacks->var_changed )
1377         d->callbacks->var_changed (d, var_get_dict_index (v), d->cb_data);
1378     }
1379 }
1380
1381
1382 /* Called from variable.c to notify the dictionary that the variable's width
1383    has changed */
1384 void
1385 dict_var_resized (const struct variable *v, int delta)
1386 {
1387   if ( var_has_vardict (v))
1388     {
1389       const struct vardict_info *vdi = var_get_vardict (v);
1390       struct dictionary *d;
1391
1392       d = vdi->dict;
1393
1394       dict_pad_values (d, var_get_case_index(v) + 1, delta);
1395
1396       if (d->changed) d->changed (d, d->changed_data);
1397       if ( d->callbacks && d->callbacks->var_resized )
1398         d->callbacks->var_resized (d, var_get_dict_index (v), delta, d->cb_data);
1399     }
1400 }
1401
1402 /* Called from variable.c to notify the dictionary that the variable's display width
1403    has changed */
1404 void
1405 dict_var_display_width_changed (const struct variable *v)
1406 {
1407   if ( var_has_vardict (v))
1408     {
1409       const struct vardict_info *vdi = var_get_vardict (v);
1410       struct dictionary *d;
1411
1412       d = vdi->dict;
1413
1414       if (d->changed) d->changed (d, d->changed_data);
1415       if ( d->callbacks && d->callbacks->var_display_width_changed )
1416         d->callbacks->var_display_width_changed (d, var_get_dict_index (v), d->cb_data);
1417     }
1418 }
1419