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