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