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