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