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