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