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